package com.ytjj.qmyx.mall.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageHelper;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.api.ResultCode;
import com.ytjj.common.constants.CopyWriterConstant;
import com.ytjj.common.constants.QueueConstants;
import com.ytjj.common.constants.SysConfigConstants;
import com.ytjj.common.dto.mqdto.AppDataStatisticsExposureDto;
import com.ytjj.common.enums.ScoreSourceEnum;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.*;
import com.ytjj.qmyx.mall.builder.MyBoolQueryBuilder;
import com.ytjj.qmyx.mall.config.CommonPropertiesConfig;
import com.ytjj.qmyx.mall.constants.DynamicConstant;
import com.ytjj.qmyx.mall.constants.EsConstant;
import com.ytjj.qmyx.mall.constants.ExpireTimeConstant;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.enums.BankerNameEnums;
import com.ytjj.qmyx.mall.enums.ProductStatusEnums;
import com.ytjj.qmyx.mall.enums.SpecialStatusEnums;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.mall.model.esmodel.DynamicEsDto;
import com.ytjj.qmyx.mall.model.request.*;
import com.ytjj.qmyx.mall.model.response.*;
import com.ytjj.qmyx.mall.service.DynamicService;
import com.ytjj.qmyx.mall.service.EsService;
import com.ytjj.qmyx.mall.service.EvaluationServive;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.utils.EsUtils;
import com.ytjj.qmyx.mall.utils.RandomUtil;
import com.ytjj.qmyx.users.client.UsersClient;
import com.ytjj.qmyx.users.mapper.UsersInfoMapper;
import com.ytjj.qmyx.users.model.AddUserScoreRequest;
import com.ytjj.qmyx.users.model.DynamicDto;
import com.ytjj.qmyx.users.model.UsersDto;
import com.ytjj.qmyx.users.model.UsersInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static org.elasticsearch.index.query.QueryBuilders.*;

@Service
@Slf4j
public class EvaluationServiceImpl implements EvaluationServive {


    @Resource
    private CopyWriterConfigUtil copyWriterConfigUtil;

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private DynamicSpecialMapper dynamicSpecialMapper;

    @Resource
    private DynamicMapper dynamicMapper;

    @Resource
    private ProductStarMapper productStarMapper;

    @Resource
    private OrdersInfoMapper ordersInfoMapper;

    @Resource
    private DynamicDao dynamicDao;

    @Resource
    private DynamicCommentMapper dynamicCommentMapper;

    @Resource
    private EvaluationProductMapper evaluationProductMapper;

    @Resource
    private EvaluationProductDao evaluationProductDao;

    @Resource
    private BankerSiteDao bankerSiteDao;

    @Resource
    private BankerSiteMapper bankerSiteMapper;

    @Resource
    private BankerColumnMapper bankerColumnMapper;

    @Resource
    private UsersClient usersClient;

    @Resource
    private BankerMapper bankerMapper;

    @Resource
    private OrderInfoDao orderInfoDao;

    private final ElasticsearchTemplate elasticsearchTemplate;

    @Resource
    private HelpWorkMapper helpWorkMapper;

    @Resource
    private ProductImgMapper productImgMapper;

    @Resource
    private EvaluationProductSpecMapper evaluationProductSpecMapper;
    @Resource
    private ProductSpecMapper productSpecMapper;

    @Autowired(required = false)
    private ProductDao productDao;

    private final OrdersService ordersService;

    @Resource
    private SysConfigUtil sysConfigUtil;

    //    @Resource
//    private RedisLockUtil redisLockUtil;
    @Resource
    private RedissonClient redissonClient;

    @Resource
    private BankerFollowMapper bankerFollowMapper;

    @Resource
    private SpecialMapper specialMapper;

    @Resource
    private EsService esService;

    private final DynamicService dynamicService;

    @Resource
    private RedisService redisService;

    @Resource
    private EvaluationFlowMapper evaluationFlowMapper;

    @Resource
    private DynamicCommentDao dynamicCommentDao;
    @Resource
    private DynamicEvaluateInfoMapper dynamicEvaluateInfoMapper;

    @Resource
    private UsersInfoMapper usersInfoMapper;

    @Resource
    private ProductServiceImpl productService;

    @Autowired
    private DynamicTopicDao dynamicTopicDao;
    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;

    @Resource
    private ProductQueryHistoryMapper productQueryHistoryMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${brokerageRatio:1.6}")
    private String brokerageRatio;
    @Value("${fixRatio:10}")
    private String fixRatio;

    public EvaluationServiceImpl(DynamicService dynamicService, ElasticsearchTemplate elasticsearchTemplate, OrdersService ordersService) {
        this.dynamicService = dynamicService;
        this.elasticsearchTemplate = elasticsearchTemplate;
        this.ordersService = ordersService;
    }


//    @Resource
//    private RedissonClient redissonClient;

    /**
     * 获取首页数据（“优质测评”，“优质品牌商”，“优质严选官”）
     *
     * @param type
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Map<String, Object> selectHomeData(String type, Integer pageNum, Integer pageSize, UsersResponse usersResponse) {
        Map<String, Object> data = new HashMap<>();
        switch (type) {
            // 优质测评
            case "EVALUATION":
                DynamicExample dynamicExample = new DynamicExample();
                dynamicExample.setOrderByClause("create_time desc");
                dynamicExample.createCriteria()
                        .andDynamicTypeEqualTo("video")
                        .andStatusEqualTo((byte) 1);                       // 审核通过
                PageHelper.startPage(pageNum, pageSize);
                List<Dynamic> dynamics = dynamicMapper.selectByExample(dynamicExample);
                Collections.shuffle(dynamics);
                List<DynamicResponse> evaluation = dynamics.stream()
                        .map(item -> {
                            DynamicResponse dynamicResponse = new DynamicResponse(item);
                            UsersDto usersDto = usersClient.getUsersInfo(item.getUserId());
                            // 用户名称
                            dynamicResponse.setUserName(usersDto.getNickname());
                            // 用户头像
                            dynamicResponse.setHeadImg(usersDto.getHeadImg());
                            log.debug(JSONObject.toJSONString(dynamicResponse));
                            return dynamicResponse;
                        })
                        .collect(Collectors.toList());
                data.put("evaluation", evaluation);
                break;
            // 优质品牌商
            case "BRAND":
                // 品牌列表
                BankerSiteExample bankerSiteExample = new BankerSiteExample();
                bankerSiteExample.createCriteria().andStatusEqualTo(1).andBankerTypeEqualTo(1);
                List<BankerSite> bankerSites = bankerSiteMapper.selectByExample(bankerSiteExample);
                bankerSites = bankerSites.stream().limit(Integer.valueOf(sysConfigUtil.getSysConfig("GOOD_BRAND_NUM")))
                        .collect(Collectors.toList());
                List<BankerSiteInfoResponse> bankerSiteInfoList = bankerSites.stream().map(item -> {
                    BankerSiteInfoResponse bankerSiteInfoResponse = new BankerSiteInfoResponse();
                    Banker banker = bankerMapper.selectByPrimaryKey(item.getBankerId());
                    BeanUtils.copyProperties(item, bankerSiteInfoResponse);
                    bankerSiteInfoResponse.setTitle(BankerNameEnums.getName(bankerSiteInfoResponse.getBankerType(), bankerSiteInfoResponse.getTitle()));
                    bankerSiteInfoResponse.setName(banker.getName());
                    bankerSiteInfoResponse.setTel(banker.getTel());
                    bankerSiteInfoResponse.setProductNum(this.getProductNumByBrand(item.getBankerId()));
                    bankerSiteInfoResponse.setFans(productDao.countFollowNumByBankerId(item.getBankerId()));
//                    bankerSiteInfoResponse.setProductNum(banker.getProductNumByBrand());
//                    bankerSiteInfoResponse.setFans(banker.getFans());
                    bankerSiteInfoResponse.setSales(banker.getSales());
                    bankerSiteInfoResponse.setStatus(banker.getStatus());
                    bankerSiteInfoResponse.setBankerType(banker.getBankerType());
                    return bankerSiteInfoResponse;
                }).collect(Collectors.toList());

                // 最新上架
                PageHelper.startPage(pageNum, pageSize);
                List<EvaluationProductResponse> evaluationProductLists = bankerSiteDao.findEvaluationListByBanker();// 根据条件是会查出积分的,要求加以筛除

                data.put("brandList", bankerSiteInfoList);
                data.put("evaluationProductList", evaluationProductLists);
                break;
            // 优质严选官
            case "QUALITY_USER":
                String key = "QUALITY_USER_LIST" + TokenUtil.getPlatformData();
                String result = redisService.get(key);
                List<UsersDto> usersDtos;
                if (!StringUtils.isBlank(result)) {
                    usersDtos = JSONArray.parseArray(result, UsersDto.class);
                } else {
                    usersDtos = usersClient.queryQualityUser(pageNum, pageSize, "ALL");
                    redisService.set(key, JSONArray.toJSONString(usersDtos));
                    redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
                }
                usersDtos.stream().map(item -> {
                    DynamicExample de = new DynamicExample();
                    de.setOrderByClause("create_time desc");
                    de.createCriteria()
                            .andStatusEqualTo((byte) 1)
                            .andUserIdEqualTo(item.getId());
                    List<Dynamic> userDynamicList = dynamicMapper.selectByExample(de);
                    // 作品总数
                    item.setProductNum(userDynamicList.size());
                    // 动态图片
                    List<String> dynamicImgs = userDynamicList.stream()
                            .limit(3)
                            .map(Dynamic::getProductImg)
                            .collect(Collectors.toList());
                    item.setDynamicImgs(dynamicImgs);
                    if (usersResponse == null) {
                        item.setIsFollow(false);
                    } else if (!"h5".equals(TokenUtil.getSource())) {
                        // 是否关注他人
                        Integer isAttention = usersClient.isAttention(usersResponse.getId(), item.getId());
                        item.setIsFollow(isAttention == 1 ? true : false);
                    } else {
                        item.setIsFollow(false);
                    }
                    return item;
                }).collect(Collectors.toList());

                if (usersDtos != null && usersDtos.size() > 0) {
                    Collections.shuffle(usersDtos);
                }
                data.put("usersDtos", usersDtos);
                break;
        }
        return data;
    }

    private Integer getProductNumByBrand(Integer bankerId) {
        Integer evaluationProductNum = Optional.ofNullable(evaluationProductDao.countQualityProductList(bankerId, TokenUtil.getPlatformData())).orElse(0);
        Integer zeroProductNum = Optional.ofNullable(evaluationProductDao.countZeroProductList(bankerId)).orElse(0);
        Integer clearProductNum = Optional.ofNullable(evaluationProductDao.countClearProductList(bankerId, TokenUtil.getPlatformData())).orElse(0);
        return ((evaluationProductNum != null) ? evaluationProductNum : 0)
                + ((zeroProductNum != null) ? zeroProductNum : 0)
                + ((clearProductNum != null) ? clearProductNum : 0);
    }


    @Override
    public DynamicResponse release(EvaluationReleaseRequest request) {
        OrdersInfo orderInfo = ordersService.getOrdersInfoById(request.getOrderInfoId());
        OrdersExample ordersExample = new OrdersExample();
        ordersExample.createCriteria()
                .andUserIdEqualTo(request.getUserId())
                .andIdEqualTo(orderInfo.getOrderId());
        List<Orders> orders = ordersMapper.selectByExample(ordersExample);
        if (orders.size() <= 0) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PUBLISH_FAIL));
        } else {
            if (DynamicConstant.IS_APPRAISE_BETWEEN.equals(orderInfo.getIsAppraise()) ||
                    DynamicConstant.IS_APPRAISE_YES.equals(orderInfo.getIsAppraise())) {

                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
            }
        }
        Dynamic dynamic = new Dynamic();
        BeanUtils.copyProperties(request, dynamic);
        dynamic.setIsReason((byte) 0);
        dynamic.setShareNum(0);
        dynamic.setCommentNum(0);
        dynamic.setPraiseNum(0);
        dynamic.setStatus((byte) 2);
        dynamic.setIsZombie((byte) 1);
        dynamic.setCreateTime(new Date());
        dynamic.setUpdateTime(new Date());
        dynamic.setImg(request.getCoverImg());
        EvaluationProductInfoResponse product = getProduct(request.getProductId(), request.getProductType());
        dynamic.setProductImg(product.getProductImg());
        dynamic.setProductName(product.getProductName());
        dynamic.setContent(request.getRecommendReason());
        dynamic.setIsZeroEvaluation(product.getIsZeroEvaluation());
        dynamicMapper.insert(dynamic);

        DynamicResponse dynamicResponse = new DynamicResponse();
        dynamicResponse.setUserName(request.getUserName());
        dynamicResponse.setHeadImg(request.getHeadImg());
        BeanUtils.copyProperties(dynamic, dynamicResponse);
        dynamicResponse.setId(dynamic.getId());
        dynamicResponse.setProdcutPrice(orderInfo.getProductPrice());
        dynamicResponse.setOriginalPrice(orderInfo.getProductOprice());
        orderInfo.setIsAppraise(DynamicConstant.IS_APPRAISE_BETWEEN);
//        ordersInfoMapper.updateByPrimaryKeySelective(orderInfo);
        orderInfoDao.updateAppraiseAndEvaluation(DynamicConstant.IS_APPRAISE_BETWEEN, 2, orderInfo.getId());
        // 有无可发布商品列表
        Integer ordersInfoCount = ordersService.getOrdersInfoCount(request.getUserId());
        if (ordersInfoCount <= 0) {
            dynamicResponse.setPublishFlag(false);
        } else {
            dynamicResponse.setPublishFlag(true);
        }
        //修改助力单状态
        if (orderInfo.getIsHelpOrder().equals(1)) {
            evaluationProductDao.updateHelpStatus(request.getUserId(), request.getProductId());
        }
        return dynamicResponse;
    }

    @Override
    public List<MyShoppingListResponse> getMyShopping(Integer status, Integer userId, Integer pageNum, Integer pageSize, Integer allFlag) {
        PageHelper.startPage(pageNum, pageSize);
        List<MyShoppingListResponse> byUserId = orderInfoDao.findByUserId(userId, status);
        log.info("===getMyShopping==={}", allFlag);
        if (null != allFlag && allFlag.equals(2)) {
            List<Dynamic> dynamicList = dynamicService.getDynamicIdsByUserId(userId);
            List<Integer> dynamicIdList = dynamicList.stream().map(Dynamic::getOrderInfoId).collect(Collectors.toList());
            byUserId = byUserId.stream().filter(s -> !dynamicIdList.contains(s.getId())).collect(Collectors.toList());
//            byUserId = byUserId.stream().filter(s -> !s.getIsEvaluation()).collect(Collectors.toList());
        }
        if (byUserId != null && byUserId.size() > 0) {
            byUserId.stream().forEach(item -> {
                EvaluationProductInfoResponse response = evaluationProductDao.findByProductAndProductType(item.getProductId(), item.getProductType());
                item.setVolume(response == null ? 0 : response.getVolume());
                // 增加图片列表
                ProductImgExample example = new ProductImgExample();
                example.setOrderByClause("sort asc");
                example.createCriteria()
                        .andProductIdEqualTo(item.getProductId());
                List<ProductImg> imgs = productImgMapper.selectByExample(example);
                item.setImgs(imgs.stream().filter(img -> "banner".equals(img.getType())).map(img -> img.getImgUrl()).limit(3).collect(Collectors.toList()));
                // 是否在流水表中已经有记录
                Integer isEvaluationFlow = evaluationFlowDao.queryIsEvaluationFlow(item.getProductId(), userId);
                item.setIsEvaluationFlow(isEvaluationFlow);
                item.setEvaluationNum(evaluationFlowDao.queryEvaluationNum(item.getProductId(), null));//该商品发测评的数量
                // 增加审核理由
                if (!"APP".equals(TokenUtil.getPlatformData().toUpperCase())) {
                    EvaluationFlow evaluationFlow = evaluationProductDao.findEvaluationStatus(item.getId(), userId);
                    if (evaluationFlow != null && evaluationFlow.getDynamicId() != null) {
                        String reason = evaluationProductDao.findReasonByDynamicId(evaluationFlow.getDynamicId());
                        item.setReason(reason);
                    }
                }

                item.setProductStatus(evaluationProductDao.findProductStatus(item.getProductId()));
                BigDecimal productPrice = BigDecimal.valueOf(Double.valueOf(item.getProductPrice())); //商品售价
                BigDecimal brokerage = productPrice.multiply(new BigDecimal(fixRatio)).setScale(4, RoundingMode.HALF_UP).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
                item.setIncomeAmount(brokerage);

                Integer dynamicStatus = dynamicDao.getDynamicByOrderInfoId(item.getId());
                if (null != dynamicStatus) {
                    item.setDynamicStatus(dynamicStatus);
                }
            });
        }
        return byUserId;
    }

    @Override
    public List<DynamicEsResponse> getDynamicInfo(Integer dynamicId, Integer pageNum, Integer pageSize) {
        BoolQueryBuilder dynamicBoolQueryBuilder = new BoolQueryBuilder();
        // 当前动态信息
        DynamicEsDto dynamicEsDto = new DynamicEsDto();
        Dynamic dynamic = dynamicMapper.selectByPrimaryKey(dynamicId);
        BeanUtils.copyProperties(dynamic, dynamicEsDto);

        dynamicBoolQueryBuilder.must(termQuery("status", ProductStatusEnums.UP.getValue()));
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(dynamicBoolQueryBuilder)
                .withPageable(pageable)
                .build();
        List<DynamicEsDto> dynamicEsDtoList = elasticsearchTemplate.queryForList(searchQuery, DynamicEsDto.class);
        dynamicEsDtoList = dynamicEsDtoList.stream().filter(item -> item.getId() != dynamicId).collect(Collectors.toList());
        Collections.shuffle(dynamicEsDtoList);
        List<DynamicEsDto> dynamicEsDtoOf = new ArrayList<>();
        dynamicEsDtoOf.addAll(dynamicEsDtoList);
        if (dynamicEsDto != null) {
            dynamicEsDtoOf.add(dynamicEsDto);
            Collections.swap(dynamicEsDtoOf, dynamicEsDtoOf.indexOf(dynamicEsDto), 0);
        }
        List<DynamicEsResponse> dynamicEsResponseList = dynamicEsDtoOf.stream().map(DynamicEsResponse::new).collect(Collectors.toList());
        dynamicEsResponseList.stream().map(item -> {

            UsersDto usersDto = usersClient.getUsersInfo(item.getUserId());
            // 用户名称
            item.setUserName(usersDto.getNickname());
            // 用户头像
            item.setHeadImg(usersDto.getHeadImg());
            // 用户性别
            item.setSex(usersDto.getSex());
            // 动态类型
            item.setDynamicType("VIDEO");

            // 是否自己发布的作品 0-非本人发布 1-本人发布
            item.setIsOneself(0);
            // 点赞
            item.setIsLike(0);

            return item;
        }).collect(Collectors.toList());
        return dynamicEsResponseList;
    }

    @Override
    public EvaluationProductResponse getProductInfo(Integer id) {
        EvaluationProduct evaluationProduct = evaluationProductDao.findById(id);
        if (evaluationProduct == null) {
            throw new ApiException(ResultCode.NO_FIND_PRODUCT);
        }
        EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(evaluationProduct);
        if (evaluationProductResponse.getStatus().byteValue() != ProductStatusEnums.UP.getValue()) {
            throw new ApiException(ResultCode.NO_PRODUCT);
        }

        ProductImgExample example = new ProductImgExample();
        example.setOrderByClause("sort asc");
        example.createCriteria().andProductIdEqualTo(id);
        List<ProductImg> evaluationProductImgList = productImgMapper.selectByExample(example);
        Map<String, List<ProductImg>> map = evaluationProductImgList.stream().collect(Collectors.groupingBy(ProductImg::getType));
        evaluationProductResponse.setImgMapList(map);

        evaluationProductResponse.setRecommend(getRecommend(evaluationProductResponse.getBankerId()));
        evaluationProductResponse.setProductNum(evaluationProductDao.countProductNumByBankerId(evaluationProductResponse.getBankerId()));
        evaluationProductResponse.setFollowNum(evaluationProductDao.countFollowNumByBankerId(evaluationProductResponse.getBankerId()));
        BankerInfoResponse bankerInfoResponse = evaluationProductDao.findBankerInfoByBankerId(evaluationProductResponse.getBankerId());
        if (bankerInfoResponse != null) {
            evaluationProductResponse.setBankerName(bankerInfoResponse.getTitle());
            evaluationProductResponse.setTitle(bankerInfoResponse.getTitle());
            evaluationProductResponse.setLogo(bankerInfoResponse.getLogo());
        }
        return evaluationProductResponse;
    }

    public List<EvaluationProductResponse> getRecommend(Integer bankerId) {
        return evaluationProductDao.getRecommend(bankerId);
    }

    @Override
    public List<EvaluationProductSpecResponse> getProductSpecList(Integer productId) {
        ProductSpecExample example = new ProductSpecExample();
        example.createCriteria()
                .andStatusEqualTo(ProductStatusEnums.UP.getValue())
                .andProductIdEqualTo(productId);
        List<ProductSpec> productSpecList = productSpecMapper.selectByExample(example);
        return productSpecList.stream().map(EvaluationProductSpecResponse::new)
                .collect(Collectors.toList());
    }

    @Override
    public BrandDataResponse getBrandData(UsersResponse currentUser, Integer bankerId) {
        BrandDataResponse brandDataResponse = new BrandDataResponse();
        // 品牌信息
        BankerSiteInfoResponse bankerSiteInfoResponse = bankerSiteDao.queryBankerSiteOne(bankerId);
        if (bankerSiteInfoResponse == null) {
            throw new ApiException("品牌信息已下架");
        }

        bankerSiteInfoResponse.setProductNum(this.getProductNumByBrand(bankerId));// 根据条件是会查出积分的,要求加以筛除
        bankerSiteInfoResponse.setFans(productDao.countFollowNumByBankerId(bankerId));
        bankerSiteInfoResponse.setTitle(BankerNameEnums.getName(bankerSiteInfoResponse.getBankerType(), bankerSiteInfoResponse.getTitle()));

        brandDataResponse.setBankerSiteInfo(bankerSiteInfoResponse);

        // 栏目列表
        BankerColumnExample bankerColumnExample = new BankerColumnExample();
        bankerColumnExample.setOrderByClause("sort asc");
        bankerColumnExample.createCriteria().andStatusEqualTo(1);
        List<BankerColumn> bankerColumns = bankerColumnMapper.selectByExample(bankerColumnExample);
        brandDataResponse.setBankerColumnList(bankerColumns);

        return brandDataResponse;
    }

    @Override
    public Boolean selectIsFollow(Integer bankerId, Integer userId) {
        BankerFollowExample bankerFollowExample = new BankerFollowExample();
        bankerFollowExample.createCriteria()
                .andBankerIdEqualTo(bankerId)
                .andUserIdEqualTo(userId);
        List<BankerFollow> bankerFollows = bankerFollowMapper.selectByExample(bankerFollowExample);
        if (!CollectionUtils.isEmpty(bankerFollows)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 清仓特卖  、 品质好货  、 0元测评
     *
     * @param bankerId
     * @param bankerColumnId
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<EvaluationProductResponse> getBrandProductList(Integer bankerId, Integer bankerColumnId,
                                                               Integer pageNum, Integer pageSize, String productName, UsersResponse usersResponse) {
        /// 查询改用户下是否在助力 && 正在助力的商品名称
        Map<String, Object> helpInfoMap = new HashMap<>();
        helpInfoMap.put("status", 0);
        if (usersResponse != null && usersResponse.getId() != null) {
            HelpWork helpWork = evaluationProductDao.getHelpWorkInfoByUserId(usersResponse.getId());
            if (helpWork != null) {
                String productText = helpWork.getProductName();
                // 正在助力
                helpInfoMap.put("status", 1);
                // 商品名称
                helpInfoMap.put("productText", productText);
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Product> evaluationProducts = evaluationProductDao.queryColumnProductList(bankerId, bankerColumnId, productName);
        List<EvaluationProductResponse> evaluationProductInfos = evaluationProducts.stream().map(item -> {
            EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(item);
            // 是0元商品1
            if (item.getIsZeroProduct() == 1) {
                evaluationProductResponse.setHelpInfoMap(helpInfoMap);
            }
            evaluationProductResponse.setStock(item.getStockEvaluation());// 0元测评用stock_evaluation代替stock
            return evaluationProductResponse;
        }).collect(Collectors.toList());
        return evaluationProductInfos;
    }

    @Override
    public Map<String, Object> queryQualityProductList(Integer bankerId, UsersResponse usersResponse) {
        Map<String, Object> result = new HashMap<>();
        /// 查询改用户下是否在助力 && 正在助力的商品名称
        Map<String, Object> helpInfoMap = new HashMap<>();
        helpInfoMap.put("status", 0);
        if (usersResponse != null && usersResponse.getId() != null) {
            HelpWork helpWork = evaluationProductDao.getHelpWorkInfoByUserId(usersResponse.getId());
            if (helpWork != null) {
                String productText = helpWork.getProductName();
                // 正在助力
                helpInfoMap.put("status", 1);
                // 商品名称
                helpInfoMap.put("productText", productText);
            }
        }
        // 只查询 品质好货
        List<Product> qualityList = evaluationProductDao.queryQualityProductList(bankerId, TokenUtil.getPlatformData());// 根据条件是会查出积分的,要求加以筛除
        List<EvaluationProductResponse> qualityProductInfos = qualityList.stream()
                .map(EvaluationProductResponse::new)
                .collect(Collectors.toList());
        // 只查询 0元测评
        List<Product> zeroList = evaluationProductDao.queryZeroProductList(bankerId);// 根据条件是会查出积分的,要求加以筛除
        List<EvaluationProductResponse> zeroProductInfos = zeroList.stream()
                .map(item -> {
                    EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(item);
                    // 是0元商品
                    if (item.getIsZeroProduct() == 1) {
                        evaluationProductResponse.setHelpInfoMap(helpInfoMap);
                    }
                    evaluationProductResponse.setStock(item.getStockEvaluation());// 0元测评用stock_evaluation代替stock
                    return evaluationProductResponse;
                })
                .collect(Collectors.toList());
        result.put("qualityProductList", qualityProductInfos);
        result.put("zeroProductList", zeroProductInfos);
        return result;
    }

    @Override
    public List<EvaluationProductResponse> queryClearProductList(Integer bankerId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        // 只查询 “清仓甩卖”  1
        List<Product> evaluationProducts = evaluationProductDao.queryClearProductList(bankerId, TokenUtil.getPlatformData());// 根据条件是会查出积分的,要求加以筛除
        List<EvaluationProductResponse> evaluationProductInfos = evaluationProducts.stream()
                .map(EvaluationProductResponse::new)
                .collect(Collectors.toList());
        return evaluationProductInfos;
    }

    @Override
    public List<EvaluationProductResponse> queryEvaluationProductList(Integer pageNum, Integer pageSize, UsersResponse usersResponse, Integer soldOut) {
        // 查询改用户下是否在助力 && 正在助力的商品名称
        Map<String, Object> helpInfoMap = new HashMap<>();
        helpInfoMap.put("status", 0);
        if (usersResponse != null && usersResponse.getId() != null) {
            HelpWork helpWork = evaluationProductDao.getHelpWorkInfoByUserId(usersResponse.getId());
            if (helpWork != null) {
                String productText = helpWork.getProductName();
                // 正在助力
                helpInfoMap.put("status", 1);
                // 商品名称
                helpInfoMap.put("productText", productText);
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Product> evaluationProducts = evaluationProductDao.findZeroProduct(soldOut);// 0元测评用stock_evaluation代替stock

        List<Product> newResultList = new ArrayList<>();
        Product firstProduct = evaluationProducts.get(0);
        newResultList.add(firstProduct);
        Collections.shuffle(evaluationProducts);
        evaluationProducts.stream().forEach(item -> {
            if (!item.getId().equals(firstProduct.getId())) {
                newResultList.add(item);
            }
        });

        List<EvaluationProductResponse> result = newResultList.stream()
                .map(item -> {
                    EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(item);
                    BankerSiteInfoResponse bankerSiteInfoResponse = bankerSiteDao.queryBankerSiteOne(evaluationProductResponse.getBankerId());
                    if (bankerSiteInfoResponse != null) {
                        evaluationProductResponse.setTitle(BankerNameEnums.getName(bankerSiteInfoResponse.getBankerType(), bankerSiteInfoResponse.getTitle()));
                        evaluationProductResponse.setLogo(bankerSiteInfoResponse.getLogo());
                    }
                    // 是否助力&&助力商品名称
                    evaluationProductResponse.setHelpInfoMap(helpInfoMap);
                    evaluationProductResponse.setStock(item.getStockEvaluation());// 0元测评用stock_evaluation代替stock
                    return evaluationProductResponse;
                })
                .collect(Collectors.toList());
        return result;
    }


    @Transactional
    @Override
    public String updateBankerFollow(Integer bankerId, Integer userId) {
        BankerFollowExample bankerFollowExample = new BankerFollowExample();
        bankerFollowExample.createCriteria()
                .andBankerIdEqualTo(bankerId)
                .andUserIdEqualTo(userId);
        List<BankerFollow> bankerFollows = bankerFollowMapper.selectByExample(bankerFollowExample);
        try {
            String productBankerFollowNumKey = RedisConstants.PRODUCT_BANKER_FOLLOW_NUM + ProductServiceImpl.PRODUCT_DETAILS_KEY + bankerId;
            redisService.delete(productBankerFollowNumKey);
        } catch (Exception e) {
            log.error("===失效供应商关注数缓存失败==={}", bankerId);
        }
        if (!CollectionUtils.isEmpty(bankerFollows)) {
            // 取消关注
            bankerFollowMapper.deleteByPrimaryKey(bankerFollows.get(0).getId());
            // 删除branker的fans数 -1
            Banker banker = bankerMapper.selectByPrimaryKey(bankerId);
            banker.setFans(banker.getFans() - 1);
            bankerMapper.updateByPrimaryKeySelective(banker);
        } else {

            // 关注
            BankerFollow bankerFollow = new BankerFollow();
            bankerFollow.setBankerId(bankerId);
            bankerFollow.setUserId(userId);
            bankerFollow.setCreateTime(new Date());
            bankerFollowMapper.insert(bankerFollow);
            // 增加branker的fans数 + 1
            Banker banker = bankerMapper.selectByPrimaryKey(bankerId);
            banker.setFans(banker.getFans() + 1);
            bankerMapper.updateByPrimaryKeySelective(banker);
            //添加积分
            return usersClient.addScore(new AddUserScoreRequest(userId, ScoreSourceEnum.FOLLOW_SHOP, bankerId));
        }
        return null;
    }

    @Override
    public List<SpecialResponse> getSpecialList() {
        SpecialExample example = new SpecialExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andTypeEqualTo("mall")
                .andStatusEqualTo(SpecialStatusEnums.INVOKE.getValue());
        List<Special> specialList = specialMapper.selectByExample(example);
        List<SpecialResponse> result = specialList.stream().map(item -> new SpecialResponse(item))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<SpecialResponse> getSpecialListByApp() {
        SpecialExample example = new SpecialExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andTypeEqualTo("app_page_v4")
                .andStatusEqualTo(SpecialStatusEnums.INVOKE.getValue());
        List<Special> specialList = specialMapper.selectByExample(example);
        List<SpecialResponse> result = specialList.stream().map(item -> new SpecialResponse(item))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<BrandListResponse> getAppBrandPavilionList(Integer pageNum, Integer pageSize, Integer specialId) {
        PageHelper.startPage(pageNum, pageSize);
        List<BrandListResponse> brandListResponses = bankerSiteDao.findBrandListResponse(specialId, specialId == -1 ? 1 : 0);
        if (brandListResponses == null || brandListResponses.size() == 0) return brandListResponses;
        if (specialId == -1) {
            Collections.shuffle(brandListResponses);
        }
        List<BrandListResponse> resultList = new ArrayList<>();
        for (BrandListResponse brandListResponse : brandListResponses) {
            brandListResponse.setCount(productDao.countByBrandId(brandListResponse.getId()));
            Random random = new Random();
            int i = random.nextInt(5);
            brandListResponse.setDiscount(BigDecimal.valueOf(i % 5 * 0.5 + 1.0).setScale(1, BigDecimal.ROUND_HALF_UP).toString());
            List<FollowBankerProductResponse> items = productDao.findListByBrandId(brandListResponse.getId(), 9, specialId != null && specialId > 0 ? specialId : null,null);
            if (!CollectionUtils.isEmpty(items)) {
                brandListResponse.setBrandProducts(items);
                resultList.add(brandListResponse);
            }
        }
        return resultList;
    }

    @Override
    public List<BrandListResponse> getAppBrandPavilionListNew(Integer pageNum, Integer pageSize, Integer specialId) {
        PageHelper.startPage(pageNum, pageSize);
        List<BrandListResponse> brandListResponses = bankerSiteDao.findBrandListResponse(specialId, specialId == -1 ? 1 : 0);
        if (brandListResponses == null || brandListResponses.size() == 0) return brandListResponses;
        if (specialId == -1) {
            Collections.shuffle(brandListResponses);
        }
        List<BrandListResponse> resultList = new ArrayList<>();
        for (BrandListResponse brandListResponse : brandListResponses) {
            brandListResponse.setCount(productDao.countByBrandId(brandListResponse.getId()));
            Random random = new Random();
            int i = random.nextInt(5);
            brandListResponse.setDiscount(BigDecimal.valueOf(i % 5 * 0.5 + 1.0).setScale(1, BigDecimal.ROUND_HALF_UP).toString());

            //通过专区找分类再找商品
            List<FollowBankerProductResponse> items = new ArrayList<>();

            if (specialId != null && specialId > 0) {
                if (redisService.get("specialId-productList" + ":" + brandListResponse.getId() + specialId) == null) {
                    items = getProductBySpecialId(brandListResponse.getId(), 9, specialId);
                } else {
                    String ids = redisService.get("specialId-productList" + ":" + brandListResponse.getId() + specialId);
                    String[] split = ids.split(",");
                    List<Integer> idList = new ArrayList<>();
                    for (String s1 : split) {
                        if (StringUtils.isNotEmpty(s1)) {
                            idList.add(Integer.valueOf(s1));
                        }
                    }
                    if (!CollectionUtils.isEmpty(idList)) {
                        items = productDao.selectProductByIds(idList);
                    }
                }
            } else {
                items = productDao.findListByBrandId(brandListResponse.getId(), 9, null,null);
            }
            if (!CollectionUtils.isEmpty(items)) {
                brandListResponse.setBrandProducts(items);
                resultList.add(brandListResponse);
            }
        }
        return resultList;
    }


    private List<FollowBankerProductResponse> getProductBySpecialId(Integer brandId, int i, Integer specialId) {
        //通过专区id找专区信息
        Special special = specialMapper.selectByPrimaryKey(specialId);
        //获取分类id
        String categoryListStr = special.getCategoryListStr();
        if (org.springframework.util.StringUtils.isEmpty(categoryListStr)) {
            return null;
        }
        String[] split = categoryListStr.split(",");
        List<Integer> ids = new ArrayList<>();
        for (String s : split) {
            ids.add(Integer.valueOf(s));
        }
        //通过专区里的分类id获取到分类对象集合
        List<ProductCategoryResp> list = productDao.selectCategoryByIds(ids);
        //分类集合进行排序(三级放二级,二级放一级里)
        List<ProductCategoryResp> productCategoryResp = productService.getProductCategoryResps(list);
        if (1 == special.getCategoryType()) {//专区类目类型为一级类目
            //获取所有的一级类目id
            List<Integer> topCategoryIds = new ArrayList<>();
            productCategoryResp.forEach(topCategory -> {
                topCategoryIds.add(topCategory.getId());
            });
            //根据一级分类id查商品
            List<FollowBankerProductResponse> productList = productDao.selectProduct2TopCategory(topCategoryIds, brandId, i);
            String id = "";
            for (FollowBankerProductResponse product : productList) {
                id = id + "," + product.getId();
            }
            redisService.set("specialId-productList" + ":" + brandId + specialId, id);
            redisService.expire("specialId-productList" + ":" + brandId + specialId, ExpireTimeConstant.CALLBACK_KEY);
            return productList;
        } else {//专区类目类型为自定义类目
            List<Integer> categoryIds = productService.getCategoryIds(productCategoryResp);
            //
            List<FollowBankerProductResponse> productList = productDao.selectProduct2Categorys(categoryIds, brandId, i);
            String id = "";
            for (FollowBankerProductResponse product : productList) {
                id = id + "," + product.getId();
            }
            redisService.set("specialId-productList" + ":" + brandId + specialId, id);
            redisService.expire("specialId-productList" + ":" + brandId + specialId, ExpireTimeConstant.CALLBACK_KEY);
            return productList;
        }
    }

    @Override
    public BrandListResponse getAppBrandPavilionInfo(Integer pageNum, Integer pageSize, Integer id) {
        String platformData = "app";
        BrandListResponse brandListResponse = bankerSiteDao.findBrandResponse(id);
        if (brandListResponse == null) return null;
        brandListResponse.setCount(productDao.countByBrandId(brandListResponse.getId()));
        Double discount = productDao.discountByBrandId(brandListResponse.getId());
        brandListResponse.setDiscount(new BigDecimal(discount * 10).setScale(1, BigDecimal.ROUND_FLOOR).stripTrailingZeros().toPlainString());
        PageHelper.startPage(pageNum, pageSize);
        brandListResponse.setBrandProducts(productDao.findListByBrandId(brandListResponse.getId(), null, null,platformData));
        return brandListResponse;
    }

    @Override
    public List<BankerSiteInfoResponse> queryBankerListById(Integer specialId) {
 /*       String key = RedisConstants.SPECID_LIST + specialId + TokenUtil.getPlatformData();
        String result = redisService.get(key);
        List<BankerSiteInfoResponse> bankerSiteInfoResponses;
        if (!StringUtils.isBlank(result)) {
            bankerSiteInfoResponses = JSONArray.parseArray(result, BankerSiteInfoResponse.class);
        } else {
            if (!"h5".equals(TokenUtil.getSource())) {
                bankerSiteInfoResponses = bankerSiteDao.findBankerSiteBySpecidlIdV2(specialId);
            } else {
                bankerSiteInfoResponses = bankerSiteDao.findBankerSiteBySpecidlId(specialId);
            }
            bankerSiteInfoResponses = bankerSiteInfoResponses.stream().map(item -> {
                item.setBankerName(item.getTitle());
                return item;
            }).collect(Collectors.toList());
            if (bankerSiteInfoResponses != null && bankerSiteInfoResponses.size() > 0) {
                for (BankerSiteInfoResponse bankerSiteInfoRespons : bankerSiteInfoResponses) {
                    // 根据条件是会查出积分的,要求加以筛除
                    List<FollowBankerProductResponse> followBankerProduct = evaluationProductDao
                            .findFollowBankerProductWithStatus(bankerSiteInfoRespons.getBankerId(), ProductStatusEnums.UP.getValue(), 3);
                    Optional.ofNullable(followBankerProduct)
                            .ifPresent(items ->
                                    {
                                        bankerSiteInfoRespons.setFollowBankerProducts(items);
                                    }
                            );
                }
            }
            redisService.set(key, JSONArray.toJSONString(bankerSiteInfoResponses));
            redisService.expire(key, Integer.valueOf(sysConfigUtil.getSysConfig(SysConfigConstants.REDIS_TIME)));
        }*/
        return new ArrayList<>();
    }

    @Override
    public List<DynamicResponse> getMyEvaluation(Integer userId, Integer pageNum, Integer pageSize, UsersResponse currentUser) {
        log.info("===pageNum={},pageSize={}", pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        Integer uid = userId;
        if (userId == null) {
            if (currentUser == null) {
                return null;
            }
            uid = currentUser.getId();
        }
        List<Dynamic> dynamicList = dynamicDao.getDynamicByUserId(uid);
        if (CollectionUtils.isEmpty(dynamicList)) {
            return new ArrayList<DynamicResponse>();
        }
        UsersDto usersInfo = usersClient.getUsersInfo(uid);
        List<DynamicResponse> result = new LinkedList<>();
        dynamicList.stream().forEach(item -> {
            DynamicResponse dynamicResponse = new DynamicResponse(item);
            if (null != currentUser) {
                dynamicResponse.setIsLike(dynamicService.isLike(item.getId(), currentUser.getId()));
            } else {
                dynamicResponse.setIsLike(0);
            }
            dynamicResponse.setUserName(usersInfo.getNickname());
            dynamicResponse.setHeadImg(usersInfo.getHeadImg());
            dynamicResponse.setVideoOrImg(Arrays.asList(item.getVideo().split(",")));
            BigDecimal productPrice = item.getProdcutPrice();//商品售价
            BigDecimal brokerage = productPrice.multiply(new BigDecimal(fixRatio)).setScale(4, RoundingMode.HALF_UP).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
            dynamicResponse.setIncomeAmount(brokerage);
            result.add(dynamicResponse);
        });
        return result;
    }

    @Override
    public void addAssistOrder(AddAssistOrderRequest request) {
        int count = evaluationProductDao.countByUserId(request.getUserId());
        if (count > 0) throw new ApiException(ResultCode.ASSIST_EXIST);
//        EvaluationProduct evaluationProduct = evaluationProductDao.findById(request.getProductId());

        EvaluationProductResponse evaluationProduct = evaluationProductDao.findByProductId(request.getProductId());
        if (evaluationProduct == null) throw new ApiException(ResultCode.NO_FIND_PRODUCT);
        if (evaluationProduct.getStockEvaluation() == null || evaluationProduct.getStockEvaluation() < 1)
            throw new ApiException("已抢光");
        HelpWork helpWork = new HelpWork();
        helpWork.setUserId(request.getUserId());
        helpWork.setProductId(evaluationProduct.getId());
        helpWork.setProductName(evaluationProduct.getProductName());
        helpWork.setProductTitle(evaluationProduct.getLongTitle());
        helpWork.setProductPrice(evaluationProduct.getPrice());
        int sectionNum = RandomUtil.getSectionNum(60, 80);
        double d = (double) sectionNum / 100;
        helpWork.setProductPriceKo(evaluationProduct.getPrice().multiply(new BigDecimal(d)).setScale(2, BigDecimal.ROUND_DOWN));
        helpWork.setHelpNumKo(0);
        helpWork.setProductImg(evaluationProduct.getProductImg());
        helpWork.setProductSpecId(request.getProductSpecId());
        Integer helpNum = evaluationProduct.getHelpNum();
        if (helpNum == null || helpNum == 0) {
            helpNum = 50;
        }
        String invalidTime = sysConfigUtil.getSysConfig(SysConfigConstants.HELP_INVALID_TIME);
        LocalDateTime day = LocalDateTime.now();
        LocalDateTime time = day.plusHours(Integer.parseInt(invalidTime));
        Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
        helpWork.setHelpNum(helpNum);
        helpWork.setInvalidTime(date);
        helpWork.setStatus(1);
        helpWork.setCreateTime(new Date());
        helpWork.setUpdateTime(new Date());
        helpWorkMapper.insert(helpWork);
    }

    @Override
    public AssistOrderResponse getAssistOrder(Integer userId) {
        //当前用户是否有助力中的助力单
//        int count = evaluationProductDao.countByUserId(userId);
//        if (count == 0) {
//            return null;
//        }
        //TODO 这里查询可能存在多个对象
        AssistOrderResponse byUserIdAndProductId = evaluationProductDao.findAssistOrderByUserId(userId);
        if (byUserIdAndProductId != null) {
            if (byUserIdAndProductId.getStatus() == 3) {
                // 查询商品状态在助力完成,到收货之前, 状态改为3
                //收货完成,测评之后,状态为4
                Integer orderStatus = evaluationProductDao.findOrderInfoStatus(byUserIdAndProductId.getOrderInfoId());
                if (orderStatus != null && orderStatus > 2) {
                    byUserIdAndProductId.setStatus(4);
                }
                if (byUserIdAndProductId.getOrderInfoId() != null) {
                    EvaluationFlow evaluationFlow = evaluationProductDao.findEvaluationStatus(byUserIdAndProductId.getOrderInfoId(), userId);
//                    Integer evaluationStatus = evaluationProductDao.findEvaluationStatus(byUserIdAndProductId.getOrderInfoId(), userId);
                    if (evaluationFlow != null && evaluationFlow.getStatus() != null) {
                        byUserIdAndProductId.setStatus(evaluationFlow.getStatus() + 3);
                    }
                    if (evaluationFlow != null && evaluationFlow.getDynamicId() != null) {
                        String reason = evaluationProductDao.findReasonByDynamicId(evaluationFlow.getDynamicId());
                        byUserIdAndProductId.setReason(reason);
                    }
                }
            }
            BankerInfoResponse response = evaluationProductDao.findBankerInfoByProductId(byUserIdAndProductId.getProductId());
            // 该产品中多少助力完成的人数
//            response.setCompleteNum(evaluationProductDao.findCompleteNumByBanderId(byUserIdAndProductId.getProductId()));
            response.setCompleteNum(new Random().nextInt(480) + 20);
            byUserIdAndProductId.addInfo(response);
            byUserIdAndProductId.setZeroStock(this.zeroEvaluation(byUserIdAndProductId.getProductId(), byUserIdAndProductId.getId(), byUserIdAndProductId.getStatus()));
        }

        return byUserIdAndProductId;
    }

    @Override
    public AssistOrderResponse getHelpWorkStatusWithStockZero(Integer userId) {
        AssistOrderResponse byUserIdAndProductId = evaluationProductDao.findAssistOrderByUserId(userId);
        if (byUserIdAndProductId != null && byUserIdAndProductId.getProductId() != null) {
            Integer stockEvaluation = evaluationProductDao.getProductStockEvaluation(byUserIdAndProductId.getProductId());
            boolean is = stockEvaluation == null ||
                    stockEvaluation != 0 ||
                    byUserIdAndProductId.getStatus() == null ||
                    byUserIdAndProductId.getId() == null ||
                    byUserIdAndProductId.getStatus() >= 3;
            //助力单状态在助力中时,并且库存为0时,将助力单状态变为失效
            if (!is) {
                evaluationProductDao.updateHelpWordZeroStockStatus(byUserIdAndProductId.getId());
                byUserIdAndProductId.setStatus(2);
                return byUserIdAndProductId;
            }
        }
        return null;
    }

    public boolean zeroEvaluation(Integer productId, Integer id, Integer status) {
        Integer stockEvaluation = evaluationProductDao.getProductStockEvaluation(productId);

        if (stockEvaluation == 0) {
//            if (status < 3) {
//            //把当前商品的助力失效
//                evaluationProductDao.updateHelpWordZeroStockStatus(id);
////            new Thread(() -> {
////                try {
////                    Thread.sleep(5000);
////                } catch (InterruptedException e) {
////                    e.printStackTrace();
////                }
////
////            });
//            }
            return true;
        }
        return false;
    }


    @Override
    public AssistOrderResponse getShareAssistOrder(UsersResponse usersResponse, Integer id) {
        AssistOrderResponse assistOrderResponse = evaluationProductDao.findHelpWordById(id);
        if (assistOrderResponse == null) throw new ApiException(ResultCode.FAILED);
        if (assistOrderResponse.getHelpNum().equals(assistOrderResponse.getHelpNumKo())) {
            throw new ApiException(ResultCode.HELP_SUCCESS_ERROR);
        }

        BankerInfoResponse response = evaluationProductDao.findBankerInfoByProductId(assistOrderResponse.getProductId());
        assistOrderResponse.addInfo(response);//供应商信息
        AssistOrderResponse assistOrderResponse1 = evaluationProductDao.findHelpWordUserInfo(assistOrderResponse.getUserId());
        assistOrderResponse.setHeadImg(assistOrderResponse1.getHeadImg());//助力发起人信息
        assistOrderResponse.setNickname(assistOrderResponse1.getNickname());//助力发起人信息

        //助力状态 1:当前用户是自己 2：已助力 3：当前用户今天已助力 4：助理中 5；已失效 6： 已完成
        Integer helpStatus;
        if (null == usersResponse) {
            helpStatus = 4;
        } else {
            helpStatus = checkIsNewUserAndHelped(usersResponse.getId(), assistOrderResponse.getUserId());
            if (helpStatus == 0) {
                Integer status = assistOrderResponse.getStatus();
                helpStatus = status == 1 ? 4 : status == 2 ? 5 : 6;
            }
        }
        Integer stockEvaluation = evaluationProductDao.getProductStockEvaluation(assistOrderResponse.getProductId());
        if (stockEvaluation == 0) helpStatus = 5;
        assistOrderResponse.setHelpStatus(helpStatus);

        return assistOrderResponse;
    }

    private void checkUserHelp(Integer userId, HelpWorkResponse helpWork) {

        //当前的助力单是当前user
        if (userId.equals(helpWork.getUserId())) {
            throw new ApiException(ResultCode.USER_MYSELF_ERROR);
        }

        //助力完成
        if (!(helpWork.getProductPrice().compareTo(BigDecimal.ZERO) == 0 || helpWork.getHelpNum() == 0) && (helpWork.getProductPriceKo().equals(helpWork.getProductPrice()) || helpWork.getHelpNum().equals(helpWork.getHelpNumKo()))) {
            throw new ApiException(ResultCode.HELP_SUCCESS_ERROR);
        }

        //助力当已失效
        if (helpWork.getInvalidTime().getTime() < System.currentTimeMillis()) {
            throw new ApiException(ResultCode.ASSIST_ERROR);
        }

        //用户是否已助力当前的助力单
        Boolean a = evaluationProductDao.existsByUserIdAndHelpWorkId(userId, helpWork.getId());
        if (a) throw new ApiException(ResultCode.YOU_HELP_ERROR);


        //用户今天是否已经助力
        Boolean helped = evaluationProductDao.checkUserTodayHelped(userId);
        if (helped) throw new ApiException(ResultCode.YOU_TODAY_HELP_ERROR);

        //已助力价格超过助力价格  或  已助力人数超过助力人数
        if (helpWork.getProductPriceKo().compareTo(helpWork.getProductPrice()) > 0 || helpWork.getHelpNumKo() > helpWork.getHelpNum()) {
            throw new ApiException(ResultCode.HELP_SUCCESS_ERROR);
        }
    }

    /**
     * @param userId
     * @param helpWorkUserId
     * @return
     */
    private Integer checkIsNewUserAndHelped(Integer userId, Integer helpWorkUserId) {
        if (userId.equals(helpWorkUserId)) return 1;

        Boolean a = evaluationProductDao.existsByUserIdAndHelpWorkId(userId, helpWorkUserId);
        if (a) return 2;

        //用今天是否已经助力
        Boolean helped = evaluationProductDao.checkUserTodayHelped(userId);
        if (helped) return 3;

        return 0;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public HelpWorkResponse userHelp(UserHelpRequest userHelpRequest) {

        HelpWorkResponse helpWork = Optional.ofNullable(evaluationProductDao.findByHelpWorkId(userHelpRequest.getHelpWorkId())).orElseThrow(() -> new ApiException("助力失败，已抢光！"));

        Product product = Optional.ofNullable(productMapper.selectByPrimaryKey(helpWork.getProductId())).orElseThrow(() -> new ApiException("助力失败，已抢光！"));
        if (product.getStockEvaluation() < 1) throw new ApiException("助力失败，已抢光！");

        checkUserHelp(userHelpRequest.getUserId(), helpWork);
        UserHelpWork userHelpWork = new UserHelpWork();

        BigDecimal productPrice = Optional.ofNullable(helpWork.getProductPrice()).orElse(BigDecimal.ZERO);//该商品需要助力的价格
        Integer helpNum = Optional.ofNullable(helpWork.getHelpNum()).orElse(0);//该商品需要助力的人数
        Integer helpNumKo = Optional.ofNullable(helpWork.getHelpNumKo()).orElse(0);//该商品已助力人数
        BigDecimal productPriceKo = Optional.ofNullable(helpWork.getProductPriceKo()).orElse(BigDecimal.ZERO);//该商品已助力价格
        BigDecimal cutPrice = this.getCutPrice(productPrice, helpNum, helpNumKo, productPriceKo);//设置砍到的价格cutPrice

        helpWork.setProductPriceKo(productPriceKo.add(cutPrice));
        helpWork.setHelpNumKo(helpNumKo + 1);

        // 给协助用户设置数据
        userHelpWork.setUserCutPrice(cutPrice);
        helpWork.setUserCutPrice(cutPrice);
        userHelpWork.setHelpWorkId(userHelpRequest.getHelpWorkId());
        userHelpWork.setUserId(userHelpRequest.getUserId());
        //添加用户助力记录
        evaluationProductDao.insertUserHelp(userHelpWork);


        //是否助力成功,或需要的助力价格=0,或需要的助力人数=0
        if (productPrice.compareTo(BigDecimal.ZERO) == 0 || helpNum == 0 || helpWork.getHelpNumKo() == helpNum || productPrice.compareTo(helpWork.getProductPriceKo()) == 0) {
            //将已助力人数设置为需要的助力人数
            helpWork.setHelpNumKo(helpWork.getHelpNum());
            //将已助力价格设置为需要的助力价格
            helpWork.setProductPriceKo(helpWork.getProductPrice());
            //todo 更新助力订单状态
//            updateHelpWorkOrder(helpWork.getProductSpecId(), helpWork, product);
            //创建订单
            this.createOrder(helpWork.getProductSpecId(), TokenUtil.getChannel(), helpWork, product, 1);
        }
        //修改助力单信息
        evaluationProductDao.updateHelpWordStatus(helpWork);
        return helpWork;
    }

    @Override
    public String userAssistHelp(UserHelpRequest userHelpRequest, Integer type) {
        HelpWorkResponse helpWork = evaluationProductDao.findByHelpWorkId(userHelpRequest.getHelpWorkId());
        Product product = productMapper.selectByPrimaryKey(helpWork.getProductId());
        helpWork.setHelpNumKo(helpWork.getHelpNumKo() + 1);
        if (type == 1) {
            //创建订单
            Integer orderInfoId = this.createOrder(helpWork.getProductSpecId(), TokenUtil.getChannel(), helpWork, product, 2);
            helpWork.setOrderInfoId(orderInfoId);
            evaluationProductDao.updateHelpWordStatu(helpWork);
        } else if (type == 2) {
            //修改助力单信息
            evaluationProductDao.updateHelpWordStatu(helpWork);
        }
        return null;
    }


    @Override
    public int insertUserHelps(UserHelpRequest userHelpRequest) {
        return evaluationProductDao.insertUserHelps(userHelpRequest);
    }

    @Override
    public HelpWork selectHelps(Integer helpWorkId) {
        return evaluationProductDao.selectHelps(helpWorkId);
    }

    private BigDecimal getCutPrice(BigDecimal productPrice, Integer helpNum, Integer helpNumKo, BigDecimal productPriceKo) {
        BigDecimal restPrice = productPrice.subtract(productPriceKo).setScale(2, BigDecimal.ROUND_HALF_UP);// 剩余助力价格
        Integer restHelpNum = helpNum - helpNumKo;// 剩余助力人数
        double cutPrice = 0.00;// 该协助用户砍到的价格
        double minPrice = 0.01;

        //设置砍到的价格cutPrice
        if (restHelpNum > 1 && restPrice.compareTo(BigDecimal.ZERO) > 0) {
            cutPrice = RandomUtil.getNextDouble(minPrice, restPrice.divide(new BigDecimal(restHelpNum), 2, BigDecimal.ROUND_HALF_UP).doubleValue());
        } else if (restHelpNum == 1 && restPrice.compareTo(BigDecimal.ZERO) > 0) {
            cutPrice = restPrice.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return new BigDecimal(cutPrice);
    }


    @Resource
    private ProductMapper productMapper;

    private Integer updateHelpWorkOrder(Integer productSpecId,
                                        HelpWorkResponse helpWorkResponse, Product product) {
        UsersDto usersDto = usersClient.getUsersInfo(helpWorkResponse.getUserId());
//        Orders orders = ordersService.
        List<Orders> ordersList = ordersInfoMapper.selectZeroEvaluationOrder(usersDto.getId(), product.getId());
        if (CollectionUtils.isEmpty(ordersList)) {
            return 0;
        }
        Orders orders = ordersList.get(0);
        orders.setOrderStatus("2");
        return null;
    }

    /**
     * 免费助力创建订单
     */
    private Integer createOrder(Integer productSpecId,
                                String channel, HelpWorkResponse helpWorkResponse, Product product, Integer isHelpOrder) {
        ProductSpec productSpec = productSpecMapper.selectByPrimaryKey(productSpecId);

        // 减库存 加销量
        // product.setStockEvaluation(product.getStockEvaluation() - 1);
//        product.setStock(product.getStock() - 1);
        product.setVolume(product.getVolume() + 1);
        productSpec.setBuySum(productSpec.getBuySum() + 1);
        productSpec.setStock(productSpec.getStock() - 1);
        product.setEvaluationOkNum(product.getEvaluationOkNum() == null ? 1 : product.getEvaluationOkNum() + 1);
        if (product.getStockEvaluation() == 0) {
            product.setEvaluationOkTime(new Date());
        }

        // 查询用户手机号
        UsersDto usersDto = usersClient.getUsersInfo(helpWorkResponse.getUserId());

        // 主订单
        Orders orders = ordersService.saveOrders(usersDto.getId(), usersDto.getTel(),
                product.getOriginalPrice(), productSpec.getPrice(), "evaluation", channel, isHelpOrder);
        // 明细订单
        OrdersInfo ordersInfo = ordersService.saveOrdersInfo(orders.getId(), product.getId(), product.getProductName(), product.getProductImg(),
                productSpec.getPrice(), product.getOriginalPrice(), product.getWarehouse(), product.getWarehouseName(),
                product.getWarehouseRule(), null, productSpec.getSkuSpec(), product.getBankerId(), productSpec.getId(),
                product.getActivityType(), null, product.getActivityMax(), product.getActivityMin(), product.getDescr(), 0, ""
                , null, product.getProductType(), isHelpOrder, productSpec.getCostPrice(), productSpec.getThreeSkuId(), product.getAppraisalType());

        productMapper.updateByPrimaryKeySelective(product);
        productSpecMapper.updateByPrimaryKeySelective(productSpec);
        helpWorkResponse.setStatus(4);
        helpWorkResponse.setOrderInfoId(ordersInfo.getId());
        //返回訂單詳情
        return ordersInfo.getId();

    }

    @Override
    public FansBankerResponse getFansBanker(Integer type, Integer userId) {
        FansBankerResponse fans = new FansBankerResponse();
        if (type == 1) {
            //我的关注
            fans.setFans(getFans(userId));
        }
        if (type == 2) {
            //关注的品牌
            List<FollowBankerResponse> followBanker = getFollowBanker(userId);
            fans.setFollowBankers(followBanker);
            //关注的品牌商列表
            List<FollowBankerResponse> followBankerList = getFollowBankerList(followBanker);
            fans.setFollowBankerList(followBankerList);
        }
        return fans;
    }

    @Override
    public Integer userHelpRequestList(UserHelpRequest userHelpRequest) {
        return evaluationProductDao.userHelpRequestList(userHelpRequest);
    }

    @Override
    public int userHelpRequest(UserHelpRequest userHelpRequest) {
        return evaluationProductDao.userHelpRequest(userHelpRequest);
    }

    @Override
    public Integer userHelpa(UserHelpRequest userHelpRequest) {
        return evaluationProductDao.userHelpa(userHelpRequest);
    }

    @Override
    public HelpWork selectHelpId(Integer helpWorkId) {
        return evaluationProductDao.selectHelpId(helpWorkId);
    }

    @Override
    public List<TrendsResponse> getFansFollowList(Integer userId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TrendsResponse> trends = evaluationProductDao.findTrendsByUserId(userId);
        if (!CollectionUtils.isEmpty(trends)) {
            List<Integer> dynamicIds = trends.stream().map(TrendsResponse::getId).collect(Collectors.toList());
            try {
                log.info("===测评曝光埋点==={}", dynamicIds.size());
                pushDynamicDataToRabbitMQ(dynamicIds);
            } catch (Exception e) {
                log.error("===测评曝光埋点异常==={}", e);
            }
        }
        return trends;
    }

    @Override
    public Integer getMyIdolNum(Integer userId) {
        Integer num = evaluationProductDao.getMyIdolNum(userId);
        return num;
    }

    @Override
    public HomePageResponse homePageSearch(Integer productId, Integer productType, Integer type, String keyword, Integer pageNum, Integer pageSize) {

        HomePageResponse homePageResponse = new HomePageResponse();
        switch (type) {
            case 1:
//                PageHelper.startPage(pageNum, pageSize);
//                List<HomePageProductResponse> products = evaluationProductDao.findHomePageProduct(keyword);
                homePageResponse.setProducts(this.searchHomePageProduct(productId, productType, keyword, pageNum, pageSize));
                break;
            case 2:
                PageHelper.startPage(pageNum, pageSize);
                List<UserResultResponse> users = searchUser(keyword);
                homePageResponse.setUsers(users);
                break;
            case 3:
                PageHelper.startPage(pageNum, pageSize);
                List<FollowBankerResponse> bankers = searchBanker(keyword);
                homePageResponse.setBankers(bankers);
                break;
        }
        return homePageResponse;
    }

    private List<HomePageProductResponse> searchHomePageProduct(Integer productId, Integer productType, String keyword, Integer pageNum, Integer pageSize) {
        BoolQueryBuilder query = new MyBoolQueryBuilder(pageNum - 1, pageSize);
        query.must(termQuery("status", ProductStatusEnums.UP.getValue() + ""));
        query.must(termsQuery("platform_data", TokenUtil.getPlatformData(), "all"));
        query.mustNot(matchQuery("activity_type", ActivityTypeEnums.CASH_SCORE.name()));// 根据条件是会查出积分的,要求加以筛除

        String labelJson = null;
        //找相似
        if (productId != null) {

            labelJson = evaluationProductDao.findLabelJsonByProductId(productId);
            if (StringUtils.isEmpty(labelJson))
                return null;
            query.must(multiMatchQuery(labelJson, "label_json"));
            query.must(termQuery("banker_column_id", "2"));
        } else {
            //首页查询
            if (StringUtils.isNotEmpty(keyword)) {
                query.must(multiMatchQuery(keyword, "product_name"));
                query.must(termQuery("banker_column_id", "2"));
            }

        }
        SearchQuery searchQuery = EsUtils.createSearchQuery(query, EsUtils.MIN_SCORE, EsConstant.MYSQL_PRODUCT);
        List<HomePageProductResponse> productActivityEsDtoList = esService.query(searchQuery, HomePageProductResponse.class);
        return productActivityEsDtoList;
    }

    @Override
    public void sellAfter(Integer productId, Integer productSpecId, Integer sum, BigDecimal productPrice) {
        // 减库存 加销量
        EvaluationProduct product = evaluationProductMapper.selectByPrimaryKey(productId);
        product.setStock(product.getStock() - sum);
        product.setVolume(product.getVolume() + sum);
        evaluationProductMapper.updateByPrimaryKeySelective(product);
        EvaluationProductSpec productSpec = evaluationProductSpecMapper.selectByPrimaryKey(productSpecId);
        productSpec.setBuySum(productSpec.getBuySum() + sum);
        productSpec.setStock(productSpec.getStock() - sum);
        evaluationProductSpecMapper.updateByPrimaryKeySelective(productSpec);
        // 加店家销量
        Banker banker = bankerMapper.selectByPrimaryKey(product.getBankerId());
        if (banker != null) {
            banker.setSales(banker.getSales() + sum);
            banker.setSalesMoney(banker.getSalesMoney().add(productPrice).setScale(2));
            bankerMapper.updateByPrimaryKeySelective(banker);
        }
    }

    @Override
    public void cancelHelpWork(Integer userId, Integer evaluationId) {
        HelpWorkExample helpWorkExample = new HelpWorkExample();
        helpWorkExample.createCriteria()
                .andUserIdEqualTo(userId)
                .andProductIdEqualTo(evaluationId)
                .andStatusEqualTo(1);
        List<HelpWork> helpWorkList = helpWorkMapper.selectByExample(helpWorkExample);
        if (!CollectionUtils.isEmpty(helpWorkList)) {
            // 取消助力单状态
            HelpWork helpWork = new HelpWork();
            helpWork.setId(helpWorkList.get(0).getId());
            helpWork.setStatus(2);
            helpWork.setUpdateTime(new Date());
            helpWorkMapper.updateByPrimaryKey(helpWork);
        }
    }

    @Override
    public List<HomePageProductResponse> homePageTypeProduct(Integer pageNum, Integer pageSize, Integer type) {
        List<HomePageProductResponse> responses = null;
        if (type == 1) {
            responses = getHotSaleProduct(pageNum, pageSize, "volume");
        }
        if (type == 2) {
            responses = getHotSaleProduct(pageNum, pageSize, "sort");
        }
        if (type == 3) {
            responses = getNewProduct(pageNum, pageSize);
        }
        if (responses != null && responses.size() > 0) {
            Collections.shuffle(responses);
        }
        return responses;
    }

    @Resource
    private EvaluationFlowDao evaluationFlowDao;

    @Override
    public CommentInfoResponse commentInfo(Integer pageNum, Integer pageSize, Integer orderInfoId) {
        // 订单详情
        CommentInfoResponse commentInfoResponse = new CommentInfoResponse();
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
        Integer productId = ordersInfo.getProductId();
        Integer totalNum = evaluationFlowDao.queryEvaluationNum(productId, null);
        Integer noNum = evaluationFlowDao.queryEvaluationNum(productId, 0);

        commentInfoResponse.setProductId(productId);
        commentInfoResponse.setProductName(ordersInfo.getProductName());
        commentInfoResponse.setProductImg(ordersInfo.getProductImg());
        commentInfoResponse.setProductPrice(ordersInfo.getProductPrice());
        commentInfoResponse.setOriginalPrice(ordersInfo.getProductOprice());
        commentInfoResponse.setGoodRadio(this.getGoodAndNoRadio(totalNum, noNum).get("goodRadio"));
        commentInfoResponse.setNoRadio(this.getGoodAndNoRadio(totalNum, noNum).get("noRadio"));
        commentInfoResponse.setTotalNum(totalNum);
        commentInfoResponse.setGoodNum(evaluationFlowDao.queryEvaluationNum(productId, 1));
        commentInfoResponse.setNotNum(noNum);
        List<EvaluationFlow> evaluationFlows = evaluationFlowDao.queryEvaluationList(productId);

        commentInfoResponse.setEvaluationFlowList(evaluationFlows.stream()
                .map(EvaluationFlowResponse::new)
                .collect(Collectors.toList()));

        commentInfoResponse.getEvaluationFlowList().stream().forEach(item -> {
            if (null != item.getDynamicId()) {
                Dynamic dynamic = dynamicMapper.selectByPrimaryKey(item.getDynamicId());
                if (null != dynamic) {
                    item.setDynamicType(dynamic.getDynamicType());
                } else {
                    item.setDynamicType("img");
                }
            } else {
                item.setDynamicType("img");
            }
        });
        return commentInfoResponse;
    }

    private Map<String, Integer> getGoodAndNoRadio(Integer totalNum, Integer noNum) {
        Map<String, Integer> radioMap = new HashMap<>();
        Integer noRadio = 0;
        Integer goodRadio = 0;
        if (totalNum != null && totalNum != 0) {
            noRadio = noNum * 100 / totalNum;
            goodRadio = 100 - noRadio;
        } else {
            goodRadio = 0;
            noRadio = 0;
        }
        radioMap.put("goodRadio", goodRadio);
        radioMap.put("noRadio", noRadio);
        return radioMap;
    }

    @Override
    public void recommend(Integer orderInfoId, Boolean isRecommend, Integer userId, String tel) {
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
        Integer count = evaluationFlowDao.queryIsRecommend(ordersInfo.getProductId(), userId);
        if (count > 0) {
            throw new ApiException("你已发起了点评，请勿重复发起!");
        }
        UsersDto usersDto = usersClient.getUsersInfo(userId);
        EvaluationFlow evaluationFlow = new EvaluationFlow();
        evaluationFlow.setProductId(ordersInfo.getProductId());
        evaluationFlow.setUserId(userId);
        evaluationFlow.setNickname(usersDto.getNickname());
        evaluationFlow.setHeadImg(usersDto.getHeadImg());
        evaluationFlow.setTel(tel);
        evaluationFlow.setRecommendTime(new Date());
        evaluationFlow.setOrderInfoId(orderInfoId);
        evaluationFlow.setStatus(1);
        evaluationFlow.setCreateTime(new Date());
        evaluationFlow.setIsRecommend(isRecommend ? 1 : 0);
        evaluationFlowMapper.insert(evaluationFlow);
    }

    @Override
    public List<SpecialResponse> specialColumn() {
        SpecialExample example = new SpecialExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andTypeEqualTo("dynamic")
                .andStatusEqualTo(SpecialStatusEnums.INVOKE.getValue());
        List<Special> specialList = specialMapper.selectByExample(example);
        List<SpecialResponse> result = specialList.stream()
                .map(item -> new SpecialResponse(item))
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<SpecialResponse> specialMallColumn() {
        SpecialExample example = new SpecialExample();
        example.setOrderByClause("sort asc");
        example.createCriteria()
                .andTypeEqualTo("mall")
                .andStatusEqualTo(SpecialStatusEnums.INVOKE.getValue());
        List<Special> specialList = specialMapper.selectByExample(example);
        List<SpecialResponse> result = specialList.stream()
                .map(item -> new SpecialResponse(item))
                .collect(Collectors.toList());
        return result;
    }

    @Resource
    private SpecialBannerMapper specialBannerMapper;

    /**
     * 测评首页
     *
     * @param specialId
     * @param h5CurrentUser
     * @return
     */
    @Override
    public EvaHomeResponse evaluationHome(Integer specialId, Integer pageNum, Integer pageSize,
                                          UsersResponse h5CurrentUser, String type, String fileType, String platformData, Integer shuffle, String categoryId) {
        EvaHomeResponse response = new EvaHomeResponse();
        // 测评专区对应的banner
        SpecialBannerExample example = new SpecialBannerExample();
        example.setOrderByClause("sort asc");
        example.createCriteria().andSpecialIdEqualTo(specialId);
        List<SpecialBanner> specialBannerList = specialBannerMapper.selectByExample(example);
        if (categoryId.equals("0")) {
            categoryId = null;
        }
        // 测评专区对应的动态
        PageHelper.startPage(pageNum, pageSize);
        List<Dynamic> dynamics = evaluationProductDao.queryDynamicById(specialId, type, fileType, platformData, categoryId);
//        if(shuffle != null && shuffle == 1) {
        Collections.shuffle(dynamics);
//        }
        if (!CollectionUtils.isEmpty(dynamics)) {
            List<Integer> dynamicIds = dynamics.stream().map(Dynamic::getId).collect(Collectors.toList());
            try {
                log.info("===测评曝光埋点==={}", dynamicIds.size());
                pushDynamicDataToRabbitMQ(dynamicIds);
            } catch (Exception e) {
                log.error("===测评曝光埋点异常==={}", e);
            }
        }
        List<DynamicResponse> dynamicList = new ArrayList<>();
        for (Dynamic dynamic : dynamics) {
            String redisKey = "userInfo:" + dynamic.getUserId();
            String usersDtoStr = null;
            try {
                usersDtoStr = redisService.get(redisKey);
            } catch (Exception e) {
            }
            UsersDto usersDto = null;
            if (StringUtils.isNotEmpty(usersDtoStr)) {
                JSONObject jsonObject = JSONObject.parseObject(usersDtoStr);
                usersDto = JSONObject.toJavaObject(jsonObject, UsersDto.class);
            } else {
                usersDto = usersClient.getUsersInfo(dynamic.getUserId());
                redisService.set(redisKey, JSONObject.toJSONString(usersDto));
                redisService.expire(redisKey, 10 * 60);
            }
            DynamicResponse dynamicResponse = new DynamicResponse(dynamic);
            if (usersDto != null) {
                dynamicResponse.setUserName(usersDto.getNickname());
                dynamicResponse.setHeadImg(usersDto.getHeadImg());
            }
            if (null != h5CurrentUser && null != h5CurrentUser.getId()) {
                dynamicResponse.setIsLike(dynamicService.isLike(dynamic.getId(), h5CurrentUser.getId()));
            }
            if (StringUtils.isEmpty(dynamicResponse.getHeadImg())) {
                dynamicResponse.setHeadImg(sysConfigUtil.getSysConfig(SysConfigConstants.DEFAULT_IMG));
            }
            dynamicList.add(dynamicResponse);
        }

        response.setSpecialBannerList(specialBannerList);
        response.setDynamicList(dynamicList);
        return response;
    }

    /**
     * 接口层面来买测评曝光量数据
     *
     * @param dynamicIds
     */
    private void pushDynamicDataToRabbitMQ(List<Integer> dynamicIds) {
//        String uuid = TokenUtil.getRequest().getHeader("uuid");
//        String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
//        String channel = TokenUtil.getChannel();
//        String source = TokenUtil.getSource();//ios/android
//
//        AppDataStatisticsExposureDto dto = new AppDataStatisticsExposureDto();
//        dto.setUuid(uuid);
//        dto.setNetworkType(null);
//        dto.setIp(ip);
//        dto.setCreateTime(new Date());
//        dto.setChannel(channel);
//        dto.setPlatform(source);
//        dto.setDynamicIds(String.join(",", dynamicIds.stream().map(String::valueOf).collect(Collectors.toList())));
//        rabbitTemplate.convertAndSend(QueueConstants.APP_DYNAMIC_EXPOSURE, JSONObject.toJSONString(dto, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
    }

    @Override
    public List<EvaluationProductResponse> zeroProduct(Integer specialId, Integer pageNum, Integer pageSize, UsersResponse currentUser, Integer soldOut) {
        // 查询改用户下是否在助力 && 正在助力的商品名称
        Map<String, Object> helpInfoMap = new HashMap<>();
        helpInfoMap.put("status", 0);
        if (currentUser != null && currentUser.getId() != null) {
            HelpWork helpWork = evaluationProductDao.getHelpWorkInfoByUserId(currentUser.getId());
            if (helpWork != null) {
                String productText = helpWork.getProductName();
                // 正在助力
                helpInfoMap.put("status", 1);
                // 商品名称
                helpInfoMap.put("productText", productText);
            }
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Product> evaluationProducts = evaluationProductDao.findZeroProductById(specialId, soldOut);
        List<EvaluationProductResponse> result = evaluationProducts.stream()
                .map(item -> {
                    EvaluationProductResponse evaluationProductResponse = new EvaluationProductResponse(item);
                    BankerSiteInfoResponse bankerSiteInfoResponse = bankerSiteDao.queryBankerSiteOne(evaluationProductResponse.getBankerId());
                    if (bankerSiteInfoResponse != null) {
                        evaluationProductResponse.setTitle(BankerNameEnums.getName(bankerSiteInfoResponse.getBankerType(), bankerSiteInfoResponse.getTitle()));
                        evaluationProductResponse.setLogo(bankerSiteInfoResponse.getLogo());
                    }
                    // 是否助力&&助力商品名称
                    evaluationProductResponse.setHelpInfoMap(helpInfoMap);
                    evaluationProductResponse.setStock(item.getStockEvaluation());// 0元测评用stock_evaluation代替stock
                    return evaluationProductResponse;
                })
                .collect(Collectors.toList());
        return result;
    }

    @Override
    public List<UsersDto> querySelection(String type, Integer pageNum, Integer pageSize, UsersResponse currentUser) {
        List<UsersDto> usersDtos = usersClient.queryQualityUser(pageNum, pageSize, type);
        usersDtos.stream().map(item -> {
            if (StringUtils.isEmpty(item.getUserSignature())) {
                item.setUserSignature("这个人很懒,什么都没写");
            }
            DynamicExample de = new DynamicExample();
            de.setOrderByClause("create_time desc");
            de.createCriteria()
                    .andStatusEqualTo((byte) 1)
                    .andUserIdEqualTo(item.getId());
            List<Dynamic> userDynamicList = dynamicMapper.selectByExample(de);

            //返回动态对象
            List<DynamicDto> dynamicList = userDynamicList.stream().map(s -> {
                DynamicDto dynamicDto = new DynamicDto();
                BeanUtils.copyProperties(s, dynamicDto);
                return dynamicDto;
            }).limit(5).collect(Collectors.toList());
//            dynamicList = dynamicList.stream().limit(5).collect(Collectors.toList());
            item.setDynamicList(dynamicList);

            // 作品总数
            item.setProductNum(userDynamicList.size());
            // 动态图片
            List<String> dynamicImgs = userDynamicList.stream()
                    .limit(3)
                    .map(Dynamic::getProductImg)
                    .collect(Collectors.toList());
            item.setDynamicImgs(dynamicImgs);
            if (currentUser == null) {
                item.setIsFollow(false);
            } else if (!"h5".equals(TokenUtil.getSource())) {
                // 是否关注他人
                Integer isAttention = usersClient.isAttention(currentUser.getId(), item.getId());
                item.setIsFollow(isAttention == 1 ? true : false);
            } else {
                item.setIsFollow(false);
            }
            return item;
        }).collect(Collectors.toList());

        if (usersDtos != null && usersDtos.size() > 0) {
            Collections.shuffle(usersDtos);
        }
        return usersDtos;
    }

    @Override
    public List<UsersDto> qualityUser(Integer pageNum, Integer pageSize, UsersResponse currentUser) {
        List<UsersDto> usersDtos = null;
        if (currentUser == null || currentUser.getId() == null) {
            try {
                usersDtos = usersClient.queryNotFollowUser(pageNum, pageSize);
            } catch (Exception e) {
            }
        } else {
            try {
                usersDtos = usersClient.queryNotFollowUser(pageNum, pageSize, currentUser.getId());
            } catch (Exception e) {
                usersDtos = usersClient.queryNotFollowUser(pageNum, pageSize);
            }
        }
        if (usersDtos != null && usersDtos.size() > 0) {
            Collections.shuffle(usersDtos);
        }
        return usersDtos;
    }

    @Override
    public List<DynamicResponse> searchDynamicData(String name, String type, String fileType, Integer pageNum,
                                                   Integer pageSize, UsersResponse currentUser) {

        BoolQueryBuilder query = new MyBoolQueryBuilder(pageNum - 1, pageSize);
        if ("IMG".equals(fileType)) {
            query.must(matchQuery("dynamic_type", "img"));
        }
        if ("VIDEO".equals(fileType)) {
            query.must(matchQuery("dynamic_type", "video"));
        }
        query.must(termQuery("status", ProductStatusEnums.UP.getValue() + ""));
//        Integer score = EsUtils.MIN_SCORE_1;
        Integer score = 4;
        if (!StringUtils.isBlank(name)) {
            query.must(multiMatchQuery(name, "product_name", "descr"));
        }
        List<DynamicEsDto> dynamicEsDtoList = null;
        if ("ALL".equals(type)) {
            SearchQuery searchQuery = EsUtils.createSortSearchQuery(query, score, "share_num", SortOrder.DESC, "mysql_dynamic");
            dynamicEsDtoList = esService.query(searchQuery, DynamicEsDto.class);
        }
        if ("NEW".equals(type)) {
            SearchQuery searchQuery = EsUtils.createSortSearchQuery(query, score, "create_time", SortOrder.DESC, "mysql_dynamic");
            dynamicEsDtoList = esService.query(searchQuery, DynamicEsDto.class);
        }
        if ("HOT".equals(type)) {
            SearchQuery searchQuery = EsUtils.createSortSearchQuery(query, score, "praise_num", SortOrder.DESC, "mysql_dynamic");
            dynamicEsDtoList = esService.query(searchQuery, DynamicEsDto.class);
        }
        List<DynamicResponse> dynamicList = dynamicEsDtoList.stream()
                .map(item -> {
                    UsersDto usersDto = usersClient.getUsersInfo(item.getUserId());
                    DynamicResponse dynamicResponse = new DynamicResponse(item);
                    if (usersDto != null) {
                        dynamicResponse.setUserName(usersDto.getNickname());
                        dynamicResponse.setHeadImg(usersDto.getHeadImg());
                    }
                    if (currentUser != null && currentUser.getId() != null) {
                        try {
                            dynamicResponse.setIsLike(dynamicService.isLike(item.getId(), currentUser.getId()));
                        } catch (Exception e) {
                            dynamicResponse.setIsLike(0);
                        }
                    } else {
                        dynamicResponse.setIsLike(0);
                    }
                    return dynamicResponse;
                }).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(dynamicList)) {
            List<Integer> dynamicIds = dynamicList.stream().map(DynamicResponse::getId).collect(Collectors.toList());
            try {
                log.info("===测评曝光埋点==={}", dynamicIds.size());
                pushDynamicDataToRabbitMQ(dynamicIds);
            } catch (Exception e) {
                log.error("===测评曝光埋点异常==={}", e);
            }
        }
        return dynamicList;
    }

    @Override
    public List<UsersDto> searchUsersData(String name, Integer pageNum, Integer pageSize, Integer userId) {
        List<UsersDto> list = usersClient.searchUserByNickName(pageNum, pageSize, name);
        if (!CollectionUtils.isEmpty(list) && null != userId) {
            list.stream().forEach(item -> {
                // 是否关注他人
                Integer isAttention = usersClient.isAttention(userId, item.getId());
                item.setIsFollow(isAttention == 1 ? true : false);
                item.setDynamicSum(countUserEvaluation(item.getId()));
            });
        }
        if (null == userId) {
            list.stream().forEach(item -> {
                // 是否关注他人
                item.setIsFollow(false);
                item.setDynamicSum(countUserEvaluation(item.getId()));
            });
        }
        return list;
    }

    private Integer countUserEvaluation(Integer userId) {
        try {
            List<Dynamic> dynamicList = dynamicDao.getDynamicByUserId(userId);
            return CollectionUtils.isEmpty(dynamicList) ? 0 : dynamicList.size();
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 搜索商品
     *
     * @param name
     * @param pageNum
     * @param pageSize
     */
    @Override
    public List<Product> searchProductData(String name, Integer pageNum, Integer pageSize,Integer mark) {
//        BoolQueryBuilder query = new MyBoolQueryBuilder(pageSize, pageNum);
//        query.must(termQuery("status", 1));
//        query.must(termsQuery("platform_data", TokenUtil.getPlatformData(), "all"));
//        query.must(wildcardQuery("product_name", name));
//        SearchQuery searchQuery = EsUtils.createSearchQuery(query, EsUtils.MIN_SCORE_1, EsConstant.MYSQL_PRODUCT);
//        List<ProductEsDto> productEsDtoList = elasticsearchTemplate.queryForList(searchQuery, ProductEsDto.class);

        List<Product> productList = new ArrayList<>();
        //需要根据地区取品
        if(null != mark && mark == 1){
            String platform = commonPropertiesConfig.getPlatformByIp();
            PageHelper.startPage(pageNum, pageSize);
            productList = productDao.searchProductByNameForProvince(TokenUtil.getPlatformData(), platform, name);
        } else {
            PageHelper.startPage(pageNum, pageSize);
            ProductExample productExample = new ProductExample();
            productExample.createCriteria().andProductNameLike("%" + name + "%")
                    .andStatusEqualTo((byte) 1)
                    .andPlatformDataIn(Arrays.asList("all",TokenUtil.getPlatformData()));
            productList = productMapper.selectByExample(productExample);
        }
        log.info("searchProductData请求参数name：{}platformData:{}",name,TokenUtil.getPlatformData());
        //保存查询结果数据
        queryProductStatisticsData(CollectionUtils.isEmpty(productList)? 2:1,name);


        if (CollectionUtils.isEmpty(productList)) {
            return productList;
        }

        //支付宝小程序搜索不显示积分兑换品
        if (StringUtils.isNotBlank(TokenUtil.getSourcePlatform()) && "zfb".equals(TokenUtil.getSourcePlatform())) {
            productList = productList.stream().filter( item -> !"CASH_SCORE".equals(item.getActivityType())).collect(Collectors.toList());
        }

        //品质好货才显示
        if (!CollectionUtils.isEmpty(productList)) {
            productList = productList.stream().filter( item -> item.getBankerColumnId() !=null && item.getBankerColumnId().equals(2)).collect(Collectors.toList());
        }

        if (CollectionUtils.isEmpty(productList)) {
            return productList;
        }

        log.info("searchProductData返回productList:{}",JSONObject.toJSON(productList));
        productList.stream().forEach(item ->{
            BigDecimal price = item.getPrice().setScale(0, BigDecimal.ROUND_DOWN);
            if (item.getPrice().subtract(price).compareTo(BigDecimal.ZERO) != 0){
                item.setPrice(item.getPrice().setScale(1,BigDecimal.ROUND_DOWN));
            }else {
                item.setPrice(item.getPrice().setScale(0,BigDecimal.ROUND_DOWN));
            }
            BigDecimal originalPrice = item.getOriginalPrice().setScale(0, BigDecimal.ROUND_DOWN);
            if (item.getOriginalPrice().subtract(originalPrice).compareTo(BigDecimal.ZERO) != 0){
                item.setOriginalPrice(item.getOriginalPrice().setScale(1,BigDecimal.ROUND_DOWN));
            }else {
                item.setOriginalPrice(item.getOriginalPrice().setScale(0,BigDecimal.ROUND_DOWN));
            }

            String headImgStr = redisService.get(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId());
            if (StringUtils.isNotBlank(headImgStr)) {
                List<String> list = JSONObject.parseArray(headImgStr, String.class);
                item.setHeadImgs(list);
            } else {
//                List<Integer> userIds = ordersDao.selectByProductId(item.getId());
//                List<String> headImgs = usersInfoMapper.selectHeadImgsByUserId(userIds);
                List<String> headImgs = usersInfoMapper.selectHeadImgs();
                String s = JSONObject.toJSONString(headImgs);
                redisService.set(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId(), s);
                redisService.expire(RedisConstants.BUY_PRODUCT_USER_HEAD_IMG + item.getId(), 60 * 60);
                item.setHeadImgs(headImgs);
            }
        });

//        List<Integer> bankerIds = productList.stream().map(Product::getBankerId).collect(Collectors.toList());
//        BankerExample bankerExample = new BankerExample();
//        bankerExample.createCriteria().andIdIn(bankerIds);
//        List<Banker> bankers = bankerMapper.selectByExample(bankerExample);
//        productList.stream().forEach(item -> {
//            List<Banker> matchList = bankers.stream().filter(s -> item.getBankerId().equals(s.getId())).collect(Collectors.toList());
//            if (!CollectionUtils.isEmpty(matchList)) {
//                item.setBankerName(matchList.get(0).getName());
//            }
//        });
        log.info("222====searchProductData返回productList:{}",JSONObject.toJSON(productList));
        return productList;
    }

    /**
     * 页面搜索统计保存
     */
    private void queryProductStatisticsData(Integer status,String queryParam) {
        ProductQueryHistory queryHistory = new ProductQueryHistory();
        HttpServletRequest request = TokenUtil.getRequest();
        queryHistory.setChannel(TokenUtil.getChannel());
        queryHistory.setUuid(TokenUtil.getUuid());
        queryHistory.setChannel(TokenUtil.getChannel());
        queryHistory.setIp(IPUtil.getIpAddress(request));
        queryHistory.setPlatform(TokenUtil.getSource());
        queryHistory.setStatus(status);
        queryHistory.setQueryParam(queryParam);
        queryHistory.setCreateTime(new Date());
        productQueryHistoryMapper.insert(queryHistory);
    }

    @Override
    public void recommendAndStar(RecommendRequest recommendRequest, Integer userId, String tel) {
        OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(recommendRequest.getOrderInfoId());
        Integer count = evaluationFlowDao.queryIsRecommend(ordersInfo.getProductId(), userId);
        if (count > 0) {
            throw new ApiException("你已发起了点评，请勿重复发起!");
        }
        UsersDto usersDto = usersClient.getUsersInfo(userId);
        EvaluationFlow evaluationFlow = new EvaluationFlow();
        evaluationFlow.setProductId(ordersInfo.getProductId());
        evaluationFlow.setUserId(userId);
        evaluationFlow.setNickname(usersDto.getNickname());
        evaluationFlow.setHeadImg(usersDto.getHeadImg());
        evaluationFlow.setTel(tel);
        evaluationFlow.setRecommendTime(new Date());
        evaluationFlow.setOrderInfoId(recommendRequest.getOrderInfoId());
        evaluationFlow.setStatus(1);
        evaluationFlow.setCreateTime(new Date());
        evaluationFlow.setIsRecommend(recommendRequest.getIsRecommend());
        evaluationFlow.setPriceStar(recommendRequest.getPriceStar());
        evaluationFlow.setQualityStar(recommendRequest.getQualityStar());
        evaluationFlow.setMatchStar(recommendRequest.getMatchStar());
        evaluationFlowMapper.insert(evaluationFlow);

        ProductStar productStar = new ProductStar();
        productStar.setMatchStar(recommendRequest.getMatchStar());
        productStar.setQualityStar(recommendRequest.getQualityStar());
        productStar.setPriceStar(recommendRequest.getPriceStar());
        productStar.setProductId(ordersInfo.getProductId());
        productStarMapper.insert(productStar);

    }

    @Override
    public EvaluationDetailsResponse evaluationDetails(Integer dynamicId, Integer pageNum, UsersResponse user) {

        Dynamic dynamicCotent = Optional.ofNullable(dynamicDao.findById(dynamicId, pageNum == null ? 0 : pageNum))
                .orElseThrow(() -> new ApiException("该测评已被删除"));
        int dynamicStatusUp = 1;
        if (dynamicCotent.getStatus() != dynamicStatusUp) {
            throw new ApiException("该测评未审核通过");
        }
        // 测评用户Id
        Integer evaluationOfficerUserId = dynamicCotent.getUserId();
        // 测评商品id
        Integer evaluationProductId = dynamicCotent.getProductId();

        // 测评用户信息
        UsersDto evaluationOfficer = usersClient.getUsersInfo(evaluationOfficerUserId);

        // 测评主要内容
        //关联的话题
        List<DynamicTopic> topics = dynamicTopicDao.getByDynamicId(dynamicCotent.getId());
        DynamicResponse evaluationDynamic = new DynamicResponse(dynamicCotent);
        evaluationDynamic.setUserName(evaluationOfficer.getNickname());
        evaluationDynamic.setHeadImg(evaluationOfficer.getHeadImg());
        evaluationDynamic.setDynamicTopics(topics);
        List<String> videos = Arrays.asList(dynamicCotent.getVideo().split(","));
        evaluationDynamic.setVideoOrImg(videos);

        Integer isAttention = 0;
        Integer isMine = 0;
        Integer isLike = 0;
        Integer countLike = 0;
        if (user != null && null != user.getId() && null != evaluationOfficerUserId) {
            /**
             * 关注按钮
             * 0 否 1 是
             */
            isAttention = usersClient.isAttention(user.getId(), evaluationOfficerUserId);

            /**
             *  是否是自己的测评
             *  0 否 1 是
             **/
            isMine = ObjectUtils.compare(user.getId(), evaluationOfficerUserId) == 0
                    ? 1 : 0;

            /**
             *  是否点赞
             *  0 否 1 是
             **/
            isLike = dynamicService.isLike(dynamicCotent.getId(), user.getId());

            /**
             * 点赞数
             **/
            countLike = Optional.ofNullable(dynamicCotent.getPraiseNum()).orElse(0);
        }


        // 测评商品信息
        Product product = Optional.ofNullable(productMapper.selectByPrimaryKey(evaluationProductId))
                .orElse(new Product());
        ProductResponse evaluationProduct = new ProductResponse(product);
        // 测评商品规格

        String productSkuSpec = "";
        if (dynamicCotent.getOrderInfoId() != null) {
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(dynamicCotent.getOrderInfoId());
            if (null != ordersInfo){
                productSkuSpec = ordersInfo.getProductSkuSpec();
            }
        }
        evaluationProduct.setSkuSpec(Optional.ofNullable(productSkuSpec).orElse(""));


        // 测评商品星数
        List<ProductStar> productStars = this.getProductStars(evaluationProductId);

        // 评论
        // 查询一级评论
        List<DynamicCommentResponse> dynamicComments = this.getDynamicComment(dynamicCotent.getId(), evaluationOfficerUserId, 1, 3, user == null ? null : user.getId());

        EvaluationDetailsResponse evaluationDetailsResponse = new EvaluationDetailsResponse();
        evaluationDetailsResponse.setEvaluationDynamic(evaluationDynamic);
        evaluationDetailsResponse.setIsAttention(isAttention);
        evaluationDetailsResponse.setIsMine(isMine);
        evaluationDetailsResponse.setEvaluationProduct(evaluationProduct);
        evaluationDetailsResponse.setProductStars(productStars);
        evaluationDetailsResponse.setDynamicComments(dynamicComments);
        evaluationDetailsResponse.setCommentNum(Optional.ofNullable(dynamicService.countComment(dynamicCotent.getId())).orElse(0));
        evaluationDetailsResponse.setIsLike(isLike);
        evaluationDetailsResponse.setCountLike(countLike);
        evaluationDetailsResponse.setWidth(dynamicCotent.getWidth());
        evaluationDetailsResponse.setHeight(dynamicCotent.getHeight());
        evaluationDetailsResponse.setAuthorId(evaluationOfficerUserId);

        if (null != user) {
            evaluationDetailsResponse = doCheckWhetherCommnetFlag(dynamicId, user.getId(), evaluationDetailsResponse);
        }
        String disableFlag = redisService.get(RedisConstants.NO_CHAT_KEY + evaluationOfficerUserId);
        evaluationDetailsResponse.setDisableFlag(1);
        if (!StringUtils.isEmpty(disableFlag) && "noChat".equals(disableFlag)) {
            evaluationDetailsResponse.setDisableFlag(2);
        }
        return evaluationDetailsResponse;
    }

    private EvaluationDetailsResponse doCheckWhetherCommnetFlag(Integer dynamicId, Integer userId, EvaluationDetailsResponse evaluationDetailsResponse) {
        List<DynamicEvaluateInfo> checkEvaluate = dynamicEvaluateInfoMapper.checkExist(dynamicId, userId);
        if (CollectionUtils.isEmpty(checkEvaluate)) {
            evaluationDetailsResponse.setWhetherCommnetFlag(0);
            return evaluationDetailsResponse;
        }
        DynamicEvaluateInfo comment = checkEvaluate.get(0);
        evaluationDetailsResponse.setWhetherCommnetFlag(1);
        evaluationDetailsResponse.setStarLevel(comment.getStarLevel());
        evaluationDetailsResponse.setScore(comment.getScore());
        return evaluationDetailsResponse;
    }

    @Resource
    private DynamicSpecialDao dynamicSpecialDao;

    @Override
    public EvaluationDetailsResponse sameEvaluation(Integer dynamicId, UsersResponse user, Integer pageNum, Integer pageSize) {
        EvaluationDetailsResponse evaluationDetailsResponse = new EvaluationDetailsResponse();
        log.info("sameEvaluation,dynamicId={}", dynamicId);
        Dynamic dynamicCotent = Optional.ofNullable(dynamicMapper.selectByPrimaryKey(dynamicId))
                .orElseThrow(() -> new ApiException("该测评已被删除"));
        int dynamicStatusUp = 1;
        if (dynamicCotent.getStatus() != dynamicStatusUp) {
            throw new ApiException("该测评未审核通过");
        }

        // 同款测评
        DynamicSpecialExample dynamicSpecialExample = new DynamicSpecialExample();
        dynamicSpecialExample
                .createCriteria()
                .andDynamicIdEqualTo(dynamicId);
        List<DynamicSpecial> dynamicSpecials = dynamicSpecialMapper.selectByExample(dynamicSpecialExample);
        if (dynamicSpecials == null || dynamicSpecials.size() == 0) return evaluationDetailsResponse;
        DynamicSpecial dynamicSpecial = dynamicSpecials.get(0);
        PageHelper.startPage(pageNum, pageSize);
        if (dynamicSpecial.getSpecialId() == null) return evaluationDetailsResponse;
        List<Dynamic> dynamics = dynamicSpecialDao.queryDynamic(dynamicSpecial.getSpecialId());

        if (!CollectionUtils.isEmpty(dynamics)) {

            List<DynamicResponse> sameEvaluation = dynamics.stream()
                    .filter(i -> !i.getId().equals(dynamicId))
                    .map(item -> {
                        DynamicResponse dynamicResponse = new DynamicResponse(item);
                        UsersDto usersDto = usersClient.getUsersInfo(item.getUserId());
                        // 用户名称
                        dynamicResponse.setUserName(usersDto.getNickname());
                        // 用户头像
                        dynamicResponse.setHeadImg(usersDto.getHeadImg());
                        // 是否点赞过该测评
                        if (null != user.getId() && null != item.getId()) {
                            dynamicResponse.setIsLike(dynamicService.isLike(item.getId(), user.getId()));
                        }
                        List<String> videos = Arrays.asList(item.getVideo().split(","));
                        dynamicResponse.setVideoOrImg(videos);
                        return dynamicResponse;
                    })
                    .collect(Collectors.toList());
            log.info("打乱同款测评顺序~~~~~");
            Collections.shuffle(sameEvaluation);
            evaluationDetailsResponse.setSameEvaluation(sameEvaluation);
        }
        return evaluationDetailsResponse;
    }

    @Override
    public DynamicResponse releasePage(EvaluationReleaseRequest request) {
        OrdersInfo orderInfo = ordersService.getOrdersInfoById(request.getOrderInfoId());
        if (orderInfo == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PUBLISH_FAIL));
        }

//        else {
//            if (DynamicConstant.IS_APPRAISE_BETWEEN.equals(orderInfo.getIsAppraise()) ||
//                    DynamicConstant.IS_APPRAISE_YES.equals(orderInfo.getIsAppraise())) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
//            }
//        }
//        List<EvaluationFlow> datas = evaluationFlowDao.queryDataByOrderInfoId(request.getOrderInfoId());
//        if (!CollectionUtils.isEmpty(datas)) {
//            for (EvaluationFlow flow : datas) {
//                if (2 == flow.getStatus() || 3 == flow.getStatus()) {
//                    throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
//                }
//            }
//        }
        DynamicExample dynamicExample = new DynamicExample();
        dynamicExample.createCriteria().andStatusEqualTo((byte) 2).andOrderInfoIdEqualTo(request.getOrderInfoId());
        List<Dynamic> dynamics = dynamicMapper.selectByExample(dynamicExample);
        if (!CollectionUtils.isEmpty(dynamics)) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
        }

        Dynamic dynamic = new Dynamic();
        Integer isReason = evaluationFlowDao.queryIsReason(request.getProductId(), request.getUserId());
        dynamic.setIsReason(isReason != null ? (byte) isReason.intValue() : null);
        dynamic.setShareNum(0);
        dynamic.setUserId(request.getUserId());
        dynamic.setCommentNum(0);
        dynamic.setPraiseNum(0);
        dynamic.setStatus((byte) 2);
        dynamic.setIsZombie((byte) 1);
        dynamic.setCreateTime(new Date());
        dynamic.setUpdateTime(new Date());
        dynamic.setImg(Optional.ofNullable(request.getCoverImg())
                .orElse(request.getVideoOrImg().get(0)));// 封面图要么前端传过来,要么选择第一张图片
        dynamic.setDynamicType(request.getDynamicType());
        EvaluationProductInfoResponse product = getProduct(request.getProductId(), request.getProductType());
        dynamic.setProductType(StringUtils.isNotEmpty(product.getActivityType()) ? 2 : 1);
        dynamic.setActivityType(orderInfo.getActivityType());
        dynamic.setOrderInfoId(request.getOrderInfoId());
        dynamic.setProductImg(product.getProductImg());
        dynamic.setProductName(product.getProductName());
        dynamic.setProdcutPrice(product.getPrice());
        dynamic.setContent(request.getRecommendReason());
        dynamic.setIsZeroEvaluation(product.getIsZeroEvaluation());
        dynamic.setActivityType(product.getActivityType());
        if (!CollectionUtils.isEmpty(request.getVideoOrImg())) {
            dynamic.setVideo(StringUtils.join(request.getVideoOrImg().toArray(), ","));
        }
//        String videos = request.getVideoOrImg().toString()
//                .replace("[", "")
//                .replace("]", "");
//        dynamic.setVideo(videos);
        dynamic.setTitle(request.getTitle());
        dynamic.setProductId(request.getProductId());
        dynamic.setProductType(request.getProductType());
        if ("video".equals(dynamic.getDynamicType())) {
            Map<String, Object> result = AliyunOSSClientUtil.getScreenshot(dynamic.getVideo());
            if (result != null && result.size() > 0) {
                dynamic.setWidth((int) result.get("videoWide"));
                dynamic.setHeight((int) result.get("videoHigh"));
            }
        }
        dynamicMapper.insert(dynamic);

        try {
            String ip = IPUtil.getIpAddress(TokenUtil.getRequest());
            String channel = TokenUtil.getChannel();
            String source = TokenUtil.getSource();//ios/android
            DynamicDto dynamicDto = new DynamicDto();
            BeanUtils.copyProperties(dynamic, dynamicDto);
            dynamicDto.setIp(ip);
            dynamicDto.setPlatform(source);
            dynamicDto.setChannel(channel);
            dynamicDto.setIsFirst(checkIsFirst(dynamic.getUserId()));
//            rabbitTemplate.convertAndSend(QueueConstants.APP_EVALUATION_ADD, JSONObject.toJSONString(dynamicDto));
        } catch (Exception e) {
            log.info("===新增动态发送rabbitmq失败===");
        }

        DynamicResponse dynamicResponse = new DynamicResponse();
        dynamicResponse.setUserName(request.getUserName());
        dynamicResponse.setHeadImg(request.getHeadImg());
        BeanUtils.copyProperties(dynamic, dynamicResponse);
        dynamicResponse.setId(dynamic.getId());
        dynamicResponse.setProdcutPrice(orderInfo.getProductPrice());
        dynamicResponse.setOriginalPrice(orderInfo.getProductOprice());
        orderInfo.setIsAppraise(DynamicConstant.IS_APPRAISE_BETWEEN);
        orderInfoDao.updateAppraiseAndEvaluation(DynamicConstant.IS_APPRAISE_BETWEEN, 2, orderInfo.getId());
        // 有无可发布商品列表
        Integer ordersInfoCount = ordersService.getOrdersInfoCount(request.getUserId());
        if (ordersInfoCount <= 0) {
            dynamicResponse.setPublishFlag(false);
        } else {
            dynamicResponse.setPublishFlag(true);
        }
        //修改助力单状态
//        if (orderInfo.getIsHelpOrder() != null && 1 == orderInfo.getIsHelpOrder()) {
//            evaluationProductDao.updateHelpStatus(request.getUserId(), request.getProductId());
//        }
        // 更新测评流水表
        EvaluationFlowExample evaluationFlowExample = new EvaluationFlowExample();
        evaluationFlowExample.createCriteria()
                .andProductIdEqualTo(request.getProductId())
                .andOrderInfoIdEqualTo(request.getOrderInfoId())
                .andStatusEqualTo(4)
                .andUserIdEqualTo(request.getUserId());
        List<EvaluationFlow> oldDatas = evaluationFlowMapper.selectByExample(evaluationFlowExample);
        EvaluationFlow evaluationFlow = new EvaluationFlow();
        if (!CollectionUtils.isEmpty(oldDatas)) {
            evaluationFlow = oldDatas.get(0);
        }
        evaluationFlow.setUserId(request.getUserId());
        log.info("===request.getCoverImg()==={}", request.getCoverImg());
        evaluationFlow.setCoverImg(request.getCoverImg());
//        evaluationFlow.setTitle(request.getTitle());
        evaluationFlow.setComment(request.getRecommendReason());
        evaluationFlow.setVideo(request.getVideo());
        evaluationFlow.setCommentTime(new Date());
        evaluationFlow.setStatus(2);
        evaluationFlow.setTitle(request.getTitle());
        // 插入动态id
        evaluationFlow.setDynamicId(dynamic.getId());
        evaluationFlow.setUpdateTime(new Date());
        evaluationFlow.setOrderInfoId(request.getOrderInfoId());
        evaluationFlow.setProductId(request.getProductId());

        UsersDto usersDto = usersClient.getUsersInfo(request.getUserId());
        evaluationFlow.setNickname(usersDto.getNickname());
        evaluationFlow.setHeadImg(usersDto.getHeadImg());
        evaluationFlow.setTel(request.getTel());
        evaluationFlow.setRecommendTime(new Date());
        evaluationFlow.setCreateTime(new Date());
        evaluationFlow.setIsRecommend(request.getIsRecommend());
        evaluationFlow.setPriceStar(request.getPriceStar());
        evaluationFlow.setQualityStar(request.getQualityStar());
        evaluationFlow.setMatchStar(request.getMatchStar());

//            evaluationFlowMapper.updateByExampleSelective(evaluationFlow, evaluationFlowExample);
        if (null != evaluationFlow.getId()) {
            evaluationFlowMapper.updateByPrimaryKey(evaluationFlow);
        } else {
            evaluationFlowMapper.insertSelective(evaluationFlow);
        }

        return dynamicResponse;
    }

    /**
     * 判断是否第一次发测评
     *
     * @param userId
     * @return 1-是第一次  0-非第一次
     */
    private Integer checkIsFirst(Integer userId) {
        DynamicExample dynamicExample = new DynamicExample();
        dynamicExample.createCriteria().andUserIdEqualTo(userId);
        List<Dynamic> dynamicList = dynamicMapper.selectByExample(dynamicExample);
        if (!CollectionUtils.isEmpty(dynamicList)) {
            return 0;
        }
        return 1;
    }

    @Override
    public EvaluationDetailsResponse moreComment(Integer dynamicId, UsersResponse user, Integer pageNum, Integer pageSize) {
        Dynamic dynamicCotent = Optional.ofNullable(dynamicMapper.selectByPrimaryKey(dynamicId))
                .orElseThrow(() -> new ApiException("该测评已被删除"));
        int dynamicStatusUp = 1;
        if (dynamicCotent.getStatus() != dynamicStatusUp) {
            throw new ApiException("该测评未审核通过");
        }
        // 测评用户Id
        Integer evaluationOfficerUserId = dynamicCotent.getUserId();

        // 评论
        // 查询一级评论
        List<DynamicCommentResponse> dynamicComments = this.getDynamicComment(dynamicId, evaluationOfficerUserId, pageNum, pageSize, user.getId());

        // 评论数量
//        Integer commentNum = RandomUtil.getSectionNum(200, 400);

        EvaluationDetailsResponse evaluationDetailsResponse = new EvaluationDetailsResponse();
        evaluationDetailsResponse.setDynamicComments(dynamicComments);
        return evaluationDetailsResponse;
    }


    private List<DynamicCommentResponse> getDynamicComment(Integer dynamicId, Integer evaluationOfficerUserId, Integer pageNum, Integer pageSize, Integer userId) {
        List<DynamicCommentResponse> parentComments = new ArrayList<>();

        DynamicCommentExample dynamicCommentExample = new DynamicCommentExample();
        dynamicCommentExample.setOrderByClause("create_time DESC");
        dynamicCommentExample.createCriteria()
                .andDynamicIdEqualTo(dynamicId)
                .andStatusEqualTo(1)
                .andPidEqualTo(0);
        PageHelper.startPage(pageNum, pageSize);
        List<DynamicComment> parentCommentList = dynamicCommentMapper.selectByExample(dynamicCommentExample);
        if (!CollectionUtils.isEmpty(parentCommentList)) {
            parentComments = parentCommentList.stream()
                    .map(item -> {
                        DynamicCommentResponse parent = new DynamicCommentResponse();
                        BeanUtils.copyProperties(item, parent);

                        // 该一级评论的用户信息
                        UsersDto usersDto = usersClient.getUsersInfo(item.getUserId());
                        parent.setNickname(usersDto.getNickname());
                        parent.setHeadImg(usersDto.getHeadImg());

                        // 评论信息
                        Map<String, Integer> parentCommentInfo =
                                this.getCommentInfo(evaluationOfficerUserId, userId, parent);
                        parent.setIsAuthor(parentCommentInfo.get("isAuthor"));
                        parent.setIsMine(parentCommentInfo.get("isMine"));
                        parent.setIsLikeComment(parentCommentInfo.get("isLikeComment"));
                        parent.setLikeNum(Optional.ofNullable(item.getLikeNum()).orElse(0));

                        // 子评论
                        List<DynamicCommentResponse> children = Optional.ofNullable(dynamicCommentDao.getChildrenByPid(parent.getId(), 3))
                                .orElse(new ArrayList<>());
                        if (!CollectionUtils.isEmpty(children)) {
                            children = children.stream().map(child -> {
                                // 子评论信息
                                Map<String, Integer> childCommentInfo = this.getCommentInfo(evaluationOfficerUserId, userId, child);

                                child.setIsAuthor(childCommentInfo.get("isAuthor"));
                                child.setIsMine(childCommentInfo.get("isMine"));
                                child.setIsLikeComment(childCommentInfo.get("isLikeComment"));
                                child.setLikeNum(Optional.ofNullable(child.getLikeNum()).orElse(0));

                                return child;
                            }).collect(Collectors.toList());
                        }
                        parent.setDynamicCommentResponses(children);
                        return parent;
                    })
                    .collect(Collectors.toList());
        }

        return parentComments;
    }

//    private List<DynamicCommentResponse> getDynamicComment(Integer dynamicId, Integer evaluationOfficerUserId, Integer userId) {
//        List<DynamicCommentResponse> dynamicComments = dynamicCommentDao.getParentComment(dynamicId, 3);
//        if (!CollectionUtils.isEmpty(dynamicComments)) {
//            dynamicComments = dynamicComments.stream()
//                    .map(parent -> {
//                        // 评论信息
//                        Map<String, Integer> parentCommentInfo =
//                                this.getCommentInfo(evaluationOfficerUserId, userId, parent);
//
//                        parent.setIsAuthor(parentCommentInfo.get("isAuthor"));
//                        parent.setIsMine(parentCommentInfo.get("isMine"));
//                        parent.setIsLikeComment(parentCommentInfo.get("isLikeComment"));
//
//                        // 子评论
//                        List<DynamicCommentResponse> children =
//                                dynamicCommentDao.getChildrenByPid(parent.getId(), 3);
//                        if (!CollectionUtils.isEmpty(children)) {
//                            children = children.stream().map(child -> {
//                                // 子评论信息
//                                Map<String, Integer> childCommentInfo = this.getCommentInfo(evaluationOfficerUserId, userId, child);
//
//                                child.setIsAuthor(childCommentInfo.get("isAuthor"));
//                                child.setIsMine(childCommentInfo.get("isMine"));
//                                child.setIsLikeComment(childCommentInfo.get("isLikeComment"));
//                                return child;
//                            }).collect(Collectors.toList());
//                        }
//                        parent.setDynamicCommentResponses(children);
//                        return parent;
//                    }).collect(Collectors.toList());
//        }
//        return dynamicComments;
//    }

    private Map<String, Integer> getCommentInfo(Integer evaluationOfficerUserId, Integer userId, DynamicCommentResponse dynamicComment) {
        Integer isMine = 0;
        Integer isLikeComment = 0;
        Integer dynamicCommentId = dynamicComment.getId();

        if (null != userId) {
            /**
             *  是否是当前用户的评论
             *  0 否 1 是
             **/
            isMine = ObjectUtils.compare(dynamicComment.getUserId(), userId) == 0
                    ? 1 : 0;
            /**
             *  是否点赞
             *  0 否 1 是
             **/
            isLikeComment = dynamicService.isLikeComment(dynamicCommentId, userId);
        }
        /**
         *  是否是测评作者的评论
         *  0 否 1 是
         **/
        int isAuthor = ObjectUtils.compare(evaluationOfficerUserId, dynamicComment.getUserId()) == 0
                ? 1 : 0;

        Map<String, Integer> data = new HashMap<>();
        data.put("isMine", isMine);
        data.put("isLikeComment", isLikeComment);
        data.put("isAuthor", isAuthor);
        return data;
    }

    private List<ProductStar> getProductStars(Integer evaluationProductId) {
        ProductStarExample productStarExample = new ProductStarExample();
        productStarExample.createCriteria()
                .andProductIdEqualTo(evaluationProductId);
        List<ProductStar> productStars = Optional.ofNullable(productStarMapper.selectByExample(productStarExample))
                .orElse(new ArrayList<>());

        productStars = productStars.stream().map(productStar -> {

            productStar.setPriceStar(Optional.ofNullable(productStar.getPriceStar())
                    .orElse(BigDecimal.valueOf(5)));
            productStar.setQualityStar(Optional.ofNullable(productStar.getQualityStar())
                    .orElse(BigDecimal.valueOf(5)));
            productStar.setMatchStar(Optional.ofNullable(productStar.getMatchStar())
                    .orElse(BigDecimal.valueOf(5)));

            return productStar;
        }).collect(Collectors.toList());

        return productStars;
    }


    @Override
    public DynamicResponse releaseEvaluation(EvaluationReleaseRequest request) {
        OrdersInfo orderInfo = ordersService.getOrdersInfoById(request.getOrderInfoId());
        if (orderInfo == null) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.PUBLISH_FAIL));
        }

//        else {
//            if (DynamicConstant.IS_APPRAISE_BETWEEN.equals(orderInfo.getIsAppraise()) ||
//                    DynamicConstant.IS_APPRAISE_YES.equals(orderInfo.getIsAppraise())) {
//                throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
//            }
//        }
//        List<EvaluationFlow> datas = evaluationFlowDao.queryDataByOrderInfoId(request.getOrderInfoId());
//        if (!CollectionUtils.isEmpty(datas)) {
//            for (EvaluationFlow flow : datas) {
//                if (2 == flow.getStatus() || 3 == flow.getStatus()) {
//                    throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
//                }
//            }
//        }
        DynamicExample dynamicExample = new DynamicExample();
        dynamicExample.createCriteria().andStatusEqualTo((byte) 2).andOrderInfoIdEqualTo(request.getOrderInfoId());
        List<Dynamic> dynamics = dynamicMapper.selectByExample(dynamicExample);
        if (!CollectionUtils.isEmpty(dynamics)) {
            throw new ApiException(copyWriterConfigUtil.getCopyWriterValue(CopyWriterConstant.ALREADY_PUBLISH));
        }


        Dynamic dynamic = new Dynamic();
        Integer isReason = evaluationFlowDao.queryIsReason(request.getProductId(), request.getUserId());
        dynamic.setIsReason(isReason != null ? (byte) isReason.intValue() : null);
        dynamic.setShareNum(0);
        dynamic.setUserId(request.getUserId());
        dynamic.setCommentNum(0);
        dynamic.setPraiseNum(0);
        dynamic.setStatus((byte) 2);
        dynamic.setIsZombie((byte) 1);
        dynamic.setCreateTime(new Date());
        dynamic.setUpdateTime(new Date());
        dynamic.setImg(request.getCoverImg());
        EvaluationProductInfoResponse product = getProduct(request.getProductId(), request.getProductType());
        dynamic.setProductImg(product.getProductImg());
        dynamic.setProductName(product.getProductName());
        dynamic.setProdcutPrice(product.getPrice());
        dynamic.setContent(request.getRecommendReason());
        dynamic.setIsZeroEvaluation(product.getIsZeroEvaluation());
        dynamic.setActivityType(product.getActivityType());
        dynamic.setVideo(request.getVideo());
//        dynamic.setTitle(request.getTitle());
        dynamic.setProductId(request.getProductId());
        dynamic.setProductType(request.getProductType());
        dynamic.setWidth(request.getWidth());
        dynamic.setHeight(request.getHeight());
        dynamicMapper.insert(dynamic);

        DynamicResponse dynamicResponse = new DynamicResponse();
        dynamicResponse.setUserName(request.getUserName());
        dynamicResponse.setHeadImg(request.getHeadImg());
        BeanUtils.copyProperties(dynamic, dynamicResponse);
        dynamicResponse.setId(dynamic.getId());
        dynamicResponse.setProdcutPrice(orderInfo.getProductPrice());
        dynamicResponse.setOriginalPrice(orderInfo.getProductOprice());
        orderInfo.setIsAppraise(DynamicConstant.IS_APPRAISE_BETWEEN);
        orderInfoDao.updateAppraiseAndEvaluation(DynamicConstant.IS_APPRAISE_BETWEEN, 2, orderInfo.getId());
        // 有无可发布商品列表
        Integer ordersInfoCount = ordersService.getOrdersInfoCount(request.getUserId());
        if (ordersInfoCount <= 0) {
            dynamicResponse.setPublishFlag(false);
        } else {
            dynamicResponse.setPublishFlag(true);
        }
        //修改助力单状态
//        if (orderInfo.getIsHelpOrder() != null && 1 == orderInfo.getIsHelpOrder()) {
//            evaluationProductDao.updateHelpStatus(request.getUserId(), request.getProductId());
//        }
        // 更新测评流水表
        EvaluationFlowExample evaluationFlowExample = new EvaluationFlowExample();
        evaluationFlowExample.createCriteria()
                .andProductIdEqualTo(request.getProductId())
                .andUserIdEqualTo(request.getUserId());
        EvaluationFlow evaluationFlow = new EvaluationFlow();
        evaluationFlow.setCoverImg(request.getCoverImg());
//        evaluationFlow.setTitle(request.getTitle());
        evaluationFlow.setComment(request.getRecommendReason());
        evaluationFlow.setVideo(request.getVideo());
        evaluationFlow.setCommentTime(new Date());
        evaluationFlow.setStatus(2);
        // 插入动态id
        evaluationFlow.setDynamicId(dynamic.getId());
        evaluationFlow.setUpdateTime(new Date());
        evaluationFlowMapper.updateByExampleSelective(evaluationFlow, evaluationFlowExample);

        return dynamicResponse;
    }

    public List<HomePageProductResponse> getHotSaleProduct(Integer pageNum, Integer pageSize, String sort) {
        BoolQueryBuilder query = new MyBoolQueryBuilder(pageNum - 1, pageSize);
        // query.must(termQuery("rec_img_flag", 1));
        query.must(termQuery("home_flag", 1));
        query.must(termQuery("banker_column_id", "2"));
        return productSearch(query, sort);
    }

    public List<HomePageProductResponse> getNewProduct(Integer pageNum, Integer pageSize) {
        BoolQueryBuilder query = new MyBoolQueryBuilder(pageNum - 1, pageSize);
        query.must(termQuery("banker_column_id", "2"));
        return productSearch(query, "create_time");
    }

    public List<HomePageProductResponse> productSearch(BoolQueryBuilder query, String sortDesc) {
        query.must(termQuery("status", 1));
        query.must(termsQuery("platform_data", TokenUtil.getPlatformData(), "all"));
        // 查询普通商品
        query.mustNot(QueryBuilders.wildcardQuery("activity_type", "*"));
//        query.mustNot(matchQuery("activity_type", ActivityTypeEnums.CASH_SCORE.name()));     // 根据条件是会查出积分的,要求加以筛除
//        query.mustNot(matchQuery("activity_type", ActivityTypeEnums.GET_SCORE.name()));     // 筛选 返积分商品
//        query.mustNot(matchQuery("activity_type", ActivityTypeEnums.RECHARGE_COUPON.name()));     // 筛选 返积分商品
        SearchQuery searchQuery = EsUtils.createSortSearchQuery(query, sortDesc, SortOrder.DESC, EsConstant.MYSQL_PRODUCT);
        List<HomePageProductResponse> productActivityEsDtoList = esService.query(searchQuery, HomePageProductResponse.class);
        return productActivityEsDtoList;
    }


    /**
     * 我关注的用户
     *
     * @param userId
     * @return
     */
    public List<FansResponse> getFans(Integer userId) {
        List<FansResponse> fans = evaluationProductDao.findFans(userId);
        return fans;
    }

    /**
     * 我关注的品牌
     *
     * @param userId
     * @return
     */
    public List<FollowBankerResponse> getFollowBanker(Integer userId) {
        List<FollowBankerResponse> followBankers = evaluationProductDao.findFollowBanker(userId);
        return followBankers;
    }

    /**
     * 我关注的品牌列表
     *
     * @param list
     * @return
     */
    public List<FollowBankerResponse> getFollowBankerList(List<FollowBankerResponse> list) {
        if (list == null || list.size() == 0) return null;
        List<FollowBankerResponse> followBankers = evaluationProductDao.findFollowBankerList(list);
        if (followBankers != null && followBankers.size() > 0) {
            followBankers.stream().forEach(item -> {
                item.setFollowBankerProducts(evaluationProductDao.findFollowBankerProduct(item.getBankerId()));
            });
        }
        return followBankers;
    }

    /**
     * 首页搜索品牌商
     *
     * @param keyword
     * @return
     */
    public List<FollowBankerResponse> searchBanker(String keyword) {
        List<FollowBankerResponse> bankers = evaluationProductDao.searchBanker(keyword);
        if (bankers != null && bankers.size() > 0) {
            bankers.stream().forEach(item -> {
                item.setFollowBankerProducts(evaluationProductDao.findFollowBankerProduct(item.getBankerId()));
            });
        }
        return bankers;
    }

    /**
     * 首页搜索用户
     *
     * @param keyword
     * @return
     */
    public List<UserResultResponse> searchUser(String keyword) {
        List<UserResultResponse> responses = evaluationProductDao.searchUser(keyword);
        if (responses != null && responses.size() > 0) {
            List<UserDynamicResponse> userDynamics = evaluationProductDao.getUserDynamic(responses);
            List<UserDynamicResponse> userDynamicCounts = evaluationProductDao.getUserDynamicCount(responses);
            responses.stream().forEach(userResult -> {
                List<String> collect = userDynamics.stream().filter(item -> item.getUserId().equals(userResult.getUserId())).map(i -> i.getProductImg()).collect(Collectors.toList());
                userResult.setDynamicImgs(collect);
                UserDynamicResponse userDynamicResponse = userDynamicCounts.stream().filter(item -> item.getUserId().equals(userResult.getUserId())).findAny().orElse(null);
                userResult.setProductNum(userDynamicResponse == null ? 0 : userDynamicResponse.getCount());
            });
        }
        return responses;
    }


    /**
     * 查找商品信息
     *
     * @param productId   商品ID
     * @param productType 商品类型
     * @return
     */
    private EvaluationProductInfoResponse getProduct(Integer productId, Integer productType) {
        EvaluationProductInfoResponse byProductAndProductType = evaluationProductDao.findByProductAndProductType(productId, productType);
        return byProductAndProductType;
    }

    @Resource
    private ForumLiveDao forumLiveDao;

    @Override
    public ForumLiveNewResponse getForumLive(Integer id, String platformData) {
        ForumLiveNewResponse forumLive = forumLiveDao.findById(id);
        List<ForumLiveInfoResponse> list = forumLiveDao.findInfoByIdSize(id, platformData);
        forumLive.setList(list);
        return forumLive;
    }

    @Override
    public List<ForumLiveInfoResponse> getForumLiveInfoList(Integer id, Integer pageNum, Integer pageSize, String platformData) {
        PageHelper.startPage(pageNum, pageSize);
        return forumLiveDao.findInfoById(id, platformData);
    }

    @Override
    public Object getZeroEvaluationNum() {
        return evaluationProductDao.getZeroEvaluation();
    }

    @Override
    public List<ForumLiveInfoResponse> randomQueryLimit(int limit, String platformData) {
        return forumLiveDao.randomQueryLimit(limit, platformData);
    }


    public CommonResult addAssistOrderId1(AddAssistOrderRequest request) {
        String lockKey = "prodcut_" + request.getProductId();
        RLock lock = null;
        try {
//            boolean lock = redisLockUtil.tryLock(lockKey, 30, 10);
            lock = redissonClient.getLock(lockKey);
            boolean b = false;
            try {
                b = lock.tryLock(0, 5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                lock.unlock();
            }
            if (!b) {
                return CommonResult.failed("当前系统繁忙，请稍后再试");
            } else {
                //先查一下该用户是否是严选官
                UsersInfo usersInfo = usersInfoMapper.selectByPrimaryKey(request.getUserId());
                HelpWorkExample helpWorkExample = new HelpWorkExample();
                helpWorkExample.createCriteria().andUserIdEqualTo(request.getUserId());
                AtomicReference<Boolean> flag = new AtomicReference<>(false);//true--说明已使用严选官权限
                if (!StringUtils.isEmpty(request.getFlag()) && null != usersInfo.getIsQuality() && usersInfo.getIsQuality().equals(1)) {
                    //查一下是否用了严选官的权限---可以助力购买一次专属商品或者不助力购买一次0元测评商品
                    List<HelpWork> helpWorks = helpWorkMapper.selectByExample(helpWorkExample);
                    helpWorks.stream().forEach(item -> {
                        if (item.getHelpNum().equals(0)) {
                            flag.set(true);
                        }
                        EvaluationProductResponse product = evaluationProductDao.findByProductId(item.getProductId());
                        if (null != product && null != product.getAppraisalType() && product.getAppraisalType().equals(2) && !item.getStatus().equals(2)) {
                            flag.set(true);
                        }
                    });
                }
                int count = evaluationProductDao.countByUserId(request.getUserId());
                if (count > 3) throw new ApiException(ResultCode.ASSIST_EXISTS);
                EvaluationProductResponse evaluationProduct = evaluationProductDao.findByProductId(request.getProductId());
                if (evaluationProduct == null) throw new ApiException(ResultCode.NO_FIND_PRODUCT);
                if (evaluationProduct.getStockEvaluation() == null || evaluationProduct.getStockEvaluation() < 1)
                    throw new ApiException("已抢光");
                HelpWork helpWork = new HelpWork();
                helpWork.setUserId(request.getUserId());
                helpWork.setProductId(evaluationProduct.getId());
                helpWork.setProductName(evaluationProduct.getProductName());
                helpWork.setProductTitle(evaluationProduct.getLongTitle());
                helpWork.setProductPrice(evaluationProduct.getPrice());
                int sectionNum = RandomUtil.getSectionNum(60, 80);
                double d = (double) sectionNum / 100;
                helpWork.setProductPriceKo(evaluationProduct.getPrice().multiply(new BigDecimal(d)).setScale(2, BigDecimal.ROUND_DOWN));
                helpWork.setHelpNumKo(0);
                helpWork.setProductImg(evaluationProduct.getProductImg());
                helpWork.setProductSpecId(request.getProductSpecId());
                Integer helpNum = evaluationProduct.getHelpNum();
                if (helpNum == null || helpNum == 0) {
                    helpNum = 50;
                }
                String invalidTime = sysConfigUtil.getSysConfig(SysConfigConstants.HELP_INVALID_TIME);
                LocalDateTime day = LocalDateTime.now();
                LocalDateTime time = day.plusHours(Integer.parseInt(invalidTime));
                Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
                helpWork.setHelpNum(helpNum);
                helpWork.setInvalidTime(date);
                helpWork.setStatus(1);
                helpWork.setCreateTime(new Date());
                helpWork.setUpdateTime(new Date());

                //用户为严选官,商品不是专属,没有使用过权限
                if (!StringUtils.isEmpty(request.getFlag()) && null != usersInfo.getIsQuality() && usersInfo.getIsQuality().equals(1) && null != evaluationProduct.getAppraisalType() && !evaluationProduct.getAppraisalType().equals(2) && !flag.get()) {
                    helpWork.setHelpNum(0);
                    helpWork.setStatus(3);
                }
                int addoctor = helpWorkMapper.insertId(helpWork);
                if (addoctor > 0) {
                    //查询一遍
                    HelpWorkExample example = new HelpWorkExample();
                    example.createCriteria().andUserIdEqualTo(request.getUserId())
                            .andProductIdEqualTo(request.getProductId())
                            .andProductSpecIdEqualTo(request.getProductSpecId());
                    example.setOrderByClause("id desc");
                    List<HelpWork> helpWorks = helpWorkMapper.selectByExample(example);
                    HelpWork helpWork1 = helpWorks.get(0);
                    Product product = productMapper.selectByPrimaryKey(helpWork1.getProductId());
                    product.setStockEvaluation(product.getStockEvaluation() - 1);
                    product.setStock(product.getStock() - 1);
                    productMapper.updateByPrimaryKeySelective(product);
                    if (!StringUtils.isEmpty(request.getFlag()) && null != usersInfo.getIsQuality() && usersInfo.getIsQuality().equals(1) && null != evaluationProduct.getAppraisalType() && !evaluationProduct.getAppraisalType().equals(2) && !flag.get()) {
                        //有特权,不需助力,直接生成
                        HelpWorkResponse helpWorkResponse = new HelpWorkResponse();
                        BeanUtils.copyProperties(helpWorks.get(0), helpWorkResponse);
                        Product product1 = productMapper.selectByPrimaryKey(helpWorkResponse.getProductId());
                        //创建订单，并修改助力单
                        //Integer orderInfoId = this.createOrder(helpWorkResponse.getProductSpecId(), TokenUtil.getChannel(), helpWorkResponse, product1, 2);
                        //helpWorkResponse.setOrderInfoId(orderInfoId);
                        evaluationProductDao.updateHelpWordStatu(helpWorkResponse);
                        //OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
                        //return CommonResult.success(ordersInfo.getOrderId());
                    }
                    return CommonResult.success(helpWorks.get(0).getId());
                }
                return CommonResult.success(addoctor);
            }
        } finally {
            if (null != lock) {
                lock.unlock();
            }
        }
    }

    @Override
    public CommonResult addAssistOrderId(AddAssistOrderRequest request) {
        String lockKey = "prodcut_" + request.getProductId();
        RLock lock = null;
        try {
            lock = redissonClient.getLock(lockKey);
            boolean b = false;
            try {
                b = lock.tryLock(0, 5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                lock.unlock();
            }
            if (!b) {
                return CommonResult.failed("当前系统繁忙，请稍后再试");
            } else {
                //先查一下该用户是否是严选官
                UsersInfo usersInfo = usersInfoMapper.selectByPrimaryKey(request.getUserId());
                if (usersInfo.getIsQuality() != 1) {
                    throw new ApiException("您还不是严选官，不能参加该活动！");
                } else {
                    HelpWorkExample helpWorkExample = new HelpWorkExample();
                    helpWorkExample.createCriteria().andUserIdEqualTo(request.getUserId());
                    AtomicReference<Boolean> flag = new AtomicReference<>(false);//true--说明已使用严选官权限
                    if (flag.get() == true) {
                        throw new ApiException("您已经已使用严选官权限！");
                    } else {
                        EvaluationProductResponse evaluationProduct = evaluationProductDao.findByProductId(request.getProductId());
                        if (evaluationProduct == null) throw new ApiException(ResultCode.NO_FIND_PRODUCT);
                        if (evaluationProduct.getStockEvaluation() == null || evaluationProduct.getStockEvaluation() < 1)
                            throw new ApiException("已抢光");
                        HelpWork helpWork = new HelpWork();
                        helpWork.setUserId(request.getUserId());
                        helpWork.setProductId(evaluationProduct.getId());
                        helpWork.setProductName(evaluationProduct.getProductName());
                        helpWork.setProductTitle(evaluationProduct.getLongTitle());
                        helpWork.setProductPrice(evaluationProduct.getPrice());
                        helpWork.setHelpNumKo(0);
                        helpWork.setProductImg(evaluationProduct.getProductImg());
                        helpWork.setProductSpecId(request.getProductSpecId());
                        String invalidTime = sysConfigUtil.getSysConfig(SysConfigConstants.HELP_INVALID_TIME);
                        LocalDateTime day = LocalDateTime.now();
                        LocalDateTime time = day.plusHours(Integer.parseInt(invalidTime));
                        Date date = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
                        helpWork.setHelpNum(evaluationProduct.getHelpNum());
                        helpWork.setInvalidTime(date);
                        if (evaluationProduct.getHelpNum() <= 0) {
                            helpWork.setStatus(4);
                        } else {
                            helpWork.setStatus(1);
                        }
                        helpWork.setCreateTime(new Date());
                        helpWork.setUpdateTime(new Date());
                        int addoctor = helpWorkMapper.insertId(helpWork);
                        if (addoctor > 0) {
                            //查询一遍
                            HelpWorkExample example = new HelpWorkExample();
                            example.createCriteria().andUserIdEqualTo(request.getUserId())
                                    .andProductIdEqualTo(request.getProductId())
                                    .andProductSpecIdEqualTo(request.getProductSpecId());
                            example.setOrderByClause("id desc");
                            List<HelpWork> helpWorks = helpWorkMapper.selectByExample(example);
                            HelpWork helpWork1 = helpWorks.get(0);
                            Product product = productMapper.selectByPrimaryKey(helpWork1.getProductId());
                            product.setStockEvaluation(product.getStockEvaluation() - 1);
                            product.setStock(product.getStock() - 1);
                            productMapper.updateByPrimaryKeySelective(product);
                            HelpWorkResponse helpWorkResponse = new HelpWorkResponse();
                            BeanUtils.copyProperties(helpWorks.get(0), helpWorkResponse);
                            Product product1 = productMapper.selectByPrimaryKey(helpWorkResponse.getProductId());
                            if(product.getHelpNum()==0){
                                //创建订单，并修改助力单
                                Integer orderInfoId = this.createOrder(helpWorkResponse.getProductSpecId(), TokenUtil.getChannel(), helpWorkResponse, product1, 2);
                                helpWorkResponse.setOrderInfoId(orderInfoId);
                                evaluationProductDao.updateHelpWordStatu(helpWorkResponse);
                                OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
                                return CommonResult.success(ordersInfo.getOrderId());
                            }
                            return CommonResult.success(helpWorks.get(0).getId());
                        }
                        return CommonResult.success(addoctor);
                    }
                }
            }
        } finally {
            if (null != lock) {
                lock.unlock();
            }
        }
    }


    @Override
    public List<AssistOrderResponse> getAssistOrderList(Integer userId) {
        List<AssistOrderResponse> byUserIdAndProductId = evaluationProductDao.findAssistOrderByUserList(userId);
        for(AssistOrderResponse b : byUserIdAndProductId){
        if (byUserIdAndProductId != null) {
            if (b.getStatus() == 3) {
                // 查询商品状态在助力完成,到收货之前, 状态改为3
                //收货完成,测评之后,状态为4
                Integer orderStatus = evaluationProductDao.findOrderInfoStatus(b.getOrderInfoId());
                if (orderStatus != null && orderStatus > 2) {
                    b.setStatus(4);
                }
                if (b.getOrderInfoId() != null) {
                    EvaluationFlow evaluationFlow = evaluationProductDao.findEvaluationStatus(b.getOrderInfoId(), userId);
                    if (evaluationFlow != null && evaluationFlow.getStatus() != null) {
                        b.setStatus(evaluationFlow.getStatus() + 3);
                    }
                    if (evaluationFlow != null && evaluationFlow.getDynamicId() != null) {
                        String reason = evaluationProductDao.findReasonByDynamicId(evaluationFlow.getDynamicId());
                        b.setReason(reason);
                    }
                }
            }
            BankerInfoResponse response = evaluationProductDao.findBankerInfoByProductId(b.getProductId());
            response.setCompleteNum(new Random().nextInt(480) + 20);
            b.addInfo(response);
            b.setZeroStock(this.zeroEvaluation(b.getProductId(), b.getId(), b.getStatus()));
        }
     }
        return byUserIdAndProductId;
    }
}
